hello-stephen commented on code in PR #71331:
URL: https://github.com/apache/doris/pull/71331#discussion_r4780389700
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java:
##########
@@ -1313,6 +1315,15 @@ public PlanFragment visitPhysicalHashAggregate(
setPlanRoot(inputPlanFragment, aggregationNode, aggregate);
if (aggregate.getStats() != null) {
aggregationNode.setCardinality((long)
aggregate.getStats().getRowCount());
+ Statistics input = aggregate.child().getStats();
+ if (input != null && aggregate.getGroupByExpressions().size() == 2
+ && aggregate.getGroupByExpressions().stream().allMatch(key
-> {
+ ColumnStatistic column =
input.findColumnStatistics(key);
+ return key instanceof SlotReference && column != null
&& !column.isUnKnown
+ && Double.isFinite(column.ndv) && column.ndv >
0;
+ })) {
+
aggregationNode.setEstimatedGroupsForLocalExchange(aggregate.getStats().getRowCount());
Review Comment:
[P2] Use grouping statistics for the snapshot being scanned
An Iceberg scan with `FOR VERSION AS OF` reads the selected snapshot.
`StatsCalculator.computeCatalogRelation` fetches column NDVs through
`StatisticsCache` using a key with no snapshot. Suppose a historical snapshot
has 10,000 repeating `(k1, k2)` groups and the current snapshot has two
distinct values per key after a fresh `ANALYZE`. The current NDVs give the
historical partial aggregate an estimate of 2.25 groups, so it qualifies on a
BE with four tasks. If each task's blocks contain all historical groups and
preaggregation stays active, the new path builds and ships four states per
group on that BE where local hash needed one.
Keep the hash fallback for versioned scans unless the NDVs describe the scan
snapshot. See `StatsCalculator.java:1434–1476,1541–1577`,
`StatisticsCache.java:150–154`, and `PluginDrivenScanNode.java:1512–1519`.
##########
fe/fe-core/src/main/java/org/apache/doris/planner/AggregationNode.java:
##########
@@ -388,6 +403,46 @@ public Pair<PlanNode, LocalExchangeType>
enforceAndDeriveLocalExchange(
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) {
+ long tasks = context.getCurrentFragmentMinInstancesPerBe();
+ if (tasks <= 1 || !Double.isFinite(estimatedGroupsForLocalExchange)
+ || estimatedGroupsForLocalExchange <= 0 ||
estimatedGroupsForLocalExchange > 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;
+ }
+
+ 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(call ->
+ call.getFn() != null && call.getFn().getBinaryType() ==
Function.BinaryType.BUILTIN
+ && !call.getParams().isDistinct() &&
call.getOrderByElements().isEmpty()
+ &&
MERGEABLE_NUMERIC_AGGREGATES.contains(call.getFnName().getFunction()));
Review Comment:
[P2] Keep overflow-sensitive SUM and AVG on local hash
This name-only check admits both floating-point `SUM`/`AVG` and saturating
`DECIMALV2 AVG`. The eligible plan has this shape.
```text
Merge AVG
Hash fragment exchange (k1, k2)
Streaming AVG(CAST(v AS DECIMALV2(27,9)))
Local passthrough
Serial file scan
```
Take two workers and four same-key scan blocks containing `7 × +8e17`, `5 ×
-8e17`, `6 × +8e17`, and `5 × -8e17`, with zeros filling the blocks. The
previous hash path can accumulate blocks arriving in that order to `2.4e18` in
one state. Passthrough puts both positive blocks on one worker, where the
`1.04e19` subtotal clips at about `9.223e18`. The other worker contributes
`-8e18`. The final `AVG` divides a different sum by the same count. An
analogous `DOUBLE` case with alternating `+1e308` and `-1e308` produces
opposite infinities that merge to `NaN`.
Check the argument type before choosing passthrough and retain the hash path
for these overloads. The round-robin routing is in
`local_exchanger.cpp:283–298`, and the accumulator behavior is in
`aggregate_function_avg.h:187–233`, `decimalv2_value.cpp:38–47,127–150`, and
`aggregate_function_sum.h:51–60`.
##########
fe/fe-core/src/test/java/org/apache/doris/planner/LocalShuffleNodeCoverageTest.java:
##########
@@ -1119,6 +1125,135 @@ public void
testAggregationNodeInheritedShuffleUsesChildDistributeExprs() {
"the grouping key must not replace the inherited child
distribution key");
}
+ /** Build the file scan -> local SUM fragment after the group slots have
been renumbered. */
+ private static class FilePartialAggregatePlan {
+ final SessionVariable session = new SessionVariable();
+ final PlanTranslatorContext ctx = Mockito.spy(new
PlanTranslatorContext());
+ final AggregateInfo info = Mockito.mock(AggregateInfo.class);
+ final FunctionCallExpr sum = plainAggregateFunction("sum");
+ final TupleDescriptor input = new TupleDescriptor(new TupleId(19));
+ final TupleDescriptor output = new TupleDescriptor(new TupleId(71));
+ final SlotRef inputKey = addStringSlot(input, 93);
+ final SlotRef inputStatus = addStringSlot(input, 101);
+ final SlotRef outputKey = addStringSlot(output, 14);
+ final SlotRef outputStatus = addStringSlot(output, 32);
+ final AggregationNode agg;
+ final FileQueryScanNode scan;
+ final DataStreamSink sink = new DataStreamSink(nextPlanNodeId());
+ final PlanFragment fragment;
+
+ FilePartialAggregatePlan() {
+ ConnectContext connect = Mockito.mock(ConnectContext.class);
+ Mockito.when(connect.getSessionVariable()).thenReturn(session);
+ Mockito.doReturn(connect).when(ctx).getConnectContext();
+ ctx.setCurrentFragmentMinInstancesPerBe(4);
+
+ scan = Mockito.mock(FileQueryScanNode.class, Mockito.withSettings()
+ .useConstructor(nextPlanNodeId(), input, "FILE_SCAN",
ScanContext.EMPTY, false, session)
+ .defaultAnswer(Mockito.CALLS_REAL_METHODS));
+ Mockito.doReturn(true).when(scan).isSerialNode();
+ Mockito.doReturn(true).when(scan).isSerialOperatorOnBe(connect);
+
+ AggregateFunction fn = Mockito.mock(AggregateFunction.class);
+
Mockito.when(fn.getBinaryType()).thenReturn(Function.BinaryType.BUILTIN);
+ Mockito.when(sum.getFn()).thenReturn(fn);
+ Mockito.when(sum.getParams()).thenReturn(new FunctionParams(false,
Collections.emptyList()));
+ Mockito.when(info.getOutputTupleId()).thenReturn(output.getId());
+ Mockito.when(info.getOutputTupleDesc()).thenReturn(output);
+ Mockito.when(info.isFirstPhase()).thenReturn(true);
+
Mockito.when(info.getGroupingExprs()).thenReturn(Lists.newArrayList(inputKey,
inputStatus));
+
Mockito.when(info.getAggregateExprs()).thenReturn(Lists.newArrayList(sum));
+ agg = new AggregationNode(nextPlanNodeId(), scan, info);
+ agg.unsetNeedsFinalize();
+ agg.setUseStreamingPreagg(true);
+ agg.setEstimatedGroupsForLocalExchange(4);
+ fragment = new PlanFragment(new PlanFragmentId(5), agg,
DataPartition.RANDOM);
+ fragment.setSink(sink);
+ partitionBy(outputKey, outputStatus);
+ }
+
+ private static SlotRef addStringSlot(TupleDescriptor tuple, int
slotId) {
+ SlotDescriptor slot = new SlotDescriptor(new SlotId(slotId),
tuple.getId());
+ slot.setType(Type.STRING);
+ tuple.addSlot(slot);
+ return new SlotRef(slot);
+ }
+
+ void partitionBy(Expr first, Expr second) {
+ DataPartition partition = new
DataPartition(TPartitionType.HASH_PARTITIONED,
+ Lists.newArrayList(first, second));
+ fragment.setOutputPartition(partition);
+ sink.setOutputPartition(partition);
+ }
+
+ void assertExchange(LocalExchangeType expected) {
+ agg.enforceAndDeriveLocalExchange(ctx, null,
LocalExchangeTypeRequire.noRequire());
+ assertChildLocalExchangeType(agg, 0, expected);
+ }
+ }
+
+ @Test
+ public void testLowCardinalityFilePartialAggregateUsesPassthrough() {
+ new
FilePartialAggregatePlan().assertExchange(LocalExchangeType.PASSTHROUGH);
Review Comment:
[P3] Exercise the translated external scan and final merge in a regression
This fixture supplies the estimate, task count, serial-scan flag, and sink
partition, so the assertion would still pass if the normal planner stopped
populating any of them. It also stops before the final merge. Add a checked-in
external-file query with known statistics that asserts `PASSTHROUGH` in
`EXPLAIN DISTRIBUTED PLAN` and compares ordered `SUM`, `AVG`, and `COUNT`
results with the explicit hash setting. Include enough scan blocks for the same
key to reach more than one task.
--
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]