hello-stephen commented on code in PR #71331:
URL: https://github.com/apache/doris/pull/71331#discussion_r4794374191
##########
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:
[P2] Recheck adaptive decimal support after workload admission
An eligible Iceberg query can select the private Decimal128 functions and
then wait in the workload queue. If the assigned BE restarts at the same
address with an older binary during that wait, `Backend.handleHbResponse` can
clear the capability before admission. `Coordinator.exec` still serializes the
original plan after `enqueue`, so `AggregationNode.toThrift` sends the private
function names. The older BE rejects the query at `AggFnEvaluator::prepare`
because its factory lacks those names. Check the assigned process and its
capability after admission, and replan both aggregation stages with the legacy
hash path if support was revoked. See `Coordinator.java:160–178,648–654` and
`vectorized_agg_fn.cpp:275–290`.
##########
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:
[P2] Keep BIGINT SUM on hash until its merge is overflow-safe
```text
Final SUM
Hash exchange on (k1, k2)
Streaming SUM(v BIGINT)
Local PASSTHROUGH
Serial Iceberg scan
```
For one group, give four successive nonempty blocks one nonzero value each
in the order `+6e18, -6e18, +6e18, -6e18`. Pad with zeroes to meet the row
threshold. Local hash sends all four blocks to one state, whose running totals
fit in BIGINT. Four-way passthrough gives each task one of those states, and
the final reducer can receive both positive states first. The ordinary SUM
merge adds them in signed 64-bit arithmetic and overflows at `12e18`, even
though the exact sum is zero. This introduces undefined behavior and an
overflow diagnostic in the UBSan build. Keep affected SUM overloads on hash or
use an overflow-safe intermediate state. See `local_exchanger.cpp:283–298` and
`aggregate_function_sum.h:51–60,189–194`.
--
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]