hello-stephen commented on code in PR #71331: URL: https://github.com/apache/doris/pull/71331#discussion_r4780872391
########## regression-test/suites/external_table_p0/iceberg/test_iceberg_low_cardinality_partial_agg.groovy: ########## @@ -0,0 +1,70 @@ +// 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. + +suite("test_iceberg_low_cardinality_partial_agg", "p0,external,doris,external_docker,external_docker_doris") { + if (!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest"))) { + return + } + + def catalog = "iceberg_partial_agg_test" + def db = "partial_agg_test" + def host = context.config.otherConfigs.get("externalEnvIp") + def restPort = context.config.otherConfigs.get("iceberg_rest_uri_port") + def s3Port = context.config.otherConfigs.get("iceberg_minio_port") + sql "drop catalog if exists ${catalog}" + sql """create catalog ${catalog} properties ( + 'type'='iceberg', 'iceberg.catalog.type'='rest', 'uri'='http://${host}:${restPort}', + 's3.access_key'='admin', 's3.secret_key'='password', 's3.region'='us-east-1', + 's3.endpoint'='http://${host}:${s3Port}')""" + try { + sql "create database if not exists ${catalog}.${db}" + sql "use ${catalog}.${db}" + sql "drop table if exists partial_groups" + sql "create table partial_groups (k1 string, k2 string, amount decimal(10,2))" + // Each file spans multiple scan blocks and contains every grouping key. + 4.times { batch -> + sql """insert into partial_groups + select if(number % 2 = 0, 'A', 'B'), if(number % 4 < 2, 'X', 'Y'), + cast(number % 4 + 1 + ${batch} as decimal(10,2)) + from numbers("number" = "32768")""" + } + sql "analyze table partial_groups with sync" + + def query = { forceHash -> """select /*+ SET_VAR(enable_local_shuffle_planner=true, + enable_local_shuffle=true, parallel_pipeline_task_num=4, + enable_external_table_batch_mode=true, num_files_in_batch_mode=1, + disable_streaming_preaggregations=false, enable_bucketed_hash_agg=false, + use_serial_exchange=false, enable_local_exchange_before_streaming_agg=${forceHash}) */ + k1, k2, sum(amount), avg(amount), count(*) from partial_groups + group by k1, k2 order by k1, k2""" } + def expected = [["A", "X", 81920.00G, 2.5000G, 32768L], ["A", "Y", 147456.00G, 4.5000G, 32768L], + ["B", "X", 114688.00G, 3.5000G, 32768L], ["B", "Y", 180224.00G, 5.5000G, 32768L]] + [false, true].each { forceHash -> + def statement = query(forceHash) + def plan = sql("explain distributed plan ${statement}").collect { it[0] }.join("\n") + // Only the immediate child of the partial aggregate determines its distribution. + def exchange = plan =~ /(?m)^\s*\d+:VAGGREGATE \(update serialize\)[^\n]*\n(?:\s*\|[^\n]*\n)*\s*\d+:VLOCAL-EXCHANGE\s*\n\s*\|\s*type: (\w+)/ + assertTrue(exchange.find(), plan) + assertEquals(forceHash ? "LOCAL_EXECUTION_HASH_SHUFFLE" : "PASSTHROUGH", exchange.group(1)) + assertEquals(expected, sql(statement)) Review Comment: [P3] Record the ordered SQL results in generated regression output The fixed rows above are compared as typed JDBC objects. The regression convention in `AGENTS.md` asks for generated `qt` output for deterministic SQL results. Keep the exchange-type assertions and record the two already-ordered result sets with named `qt` checks and a generated `.out` file. ########## fe/fe-core/src/main/java/org/apache/doris/planner/AddLocalExchange.java: ########## @@ -83,13 +84,15 @@ public void addLocalExchange(FragmentIdMapping<DistributedPlan> distributedPlans PlanTranslatorContext context) { for (DistributedPlan plan : distributedPlans.values()) { PipelineDistributedPlan pipePlan = (PipelineDistributedPlan) plan; - long maxPerBeInstances = pipePlan.getInstanceJobs().stream() + LongSummaryStatistics instancesPerBe = pipePlan.getInstanceJobs().stream() .collect(java.util.stream.Collectors.groupingBy( j -> j.getAssignedWorker().id(), java.util.stream.Collectors.counting())) - .values().stream().mapToLong(Long::longValue).max().orElse(0); + .values().stream().mapToLong(Long::longValue).summaryStatistics(); + long maxPerBeInstances = instancesPerBe.getMax(); if (maxPerBeInstances <= 1) { continue; } + context.setCurrentFragmentMinInstancesPerBe(instancesPerBe.getMin()); Review Comment: [P2] Cap the passthrough decision by executor capacity A pooled file scan can get 64 assigned tasks on a BE with eight pipeline executor threads. `SessionVariable.java:4857–4881` permits the explicit setting, and `AbstractUnassignedScanJob.java:312–317` uses it for pooled scans. With eight distinct values per key and all 64 pairs present, the correlation-adjusted estimate is 36. The raw minimum of 64 admits passthrough even when the hash partitions already keep all eight executor threads busy. If repeated scan blocks contain every group and streaming preaggregation stays active, the 64 passthrough tasks emit 4,096 partial states per BE. Local hash emits 64 because each key pair belongs to one task. With two 4 KiB string keys, the uncompressed key payload of those states grows from 512 KiB to 32 MiB. Cap the eligibility threshold by the backend executor capacity, using the same capacity lookup as the bucket-parallelism check in this class. ########## fe/fe-core/src/main/java/org/apache/doris/planner/AggregationNode.java: ########## @@ -388,6 +401,67 @@ 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; + } + + 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) { + 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); + } + + 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": + // Floating-point overflow and DecimalV2 saturation can depend on how rows are split. + Type[] args = fn.getArgs(); + return args.length == 1 && (args[0].isFixedPointType() || args[0].isDecimalV3()); Review Comment: [P2] Keep overflow-prone Decimal128 accumulators on local hash ```text Final AVG Hash fragment exchange (k1, k2) Streaming AVG(amount DECIMAL(38,4)) Local passthrough Serial file scan ``` With Decimal256 disabled, consider two tasks and four consecutive scan blocks with the same group. Give those blocks one nonzero value each, in the order `+9e33, -9e33, +9e33, -9e33`, and fill the remaining rows with zeros. One state can consume the blocks in that order with a representable running subtotal and return zero. Round-robin passthrough puts both positive blocks on one task and both negative blocks on the other. Each subtotal reaches a scaled magnitude of `1.8e38`, beyond the signed Int128 limit of about `1.70e38`. `Avg.java:88–107` selects Decimal128 for this overload, and `aggregate_function_avg.h:187–201` reaches the signed addition in `core/types.h:366–368`. That addition is instrumented in the ASAN/UBSan BE build. SUM has the same Decimal128 state-width issue. Keep these overloads on the prior hash path when they use a Decimal128 accumulator, or use an overflow-safe partial state. ########## regression-test/suites/external_table_p0/iceberg/test_iceberg_low_cardinality_partial_agg.groovy: ########## @@ -0,0 +1,70 @@ +// 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. + +suite("test_iceberg_low_cardinality_partial_agg", "p0,external,doris,external_docker,external_docker_doris") { + if (!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest"))) { + return + } + + def catalog = "iceberg_partial_agg_test" + def db = "partial_agg_test" + def host = context.config.otherConfigs.get("externalEnvIp") + def restPort = context.config.otherConfigs.get("iceberg_rest_uri_port") + def s3Port = context.config.otherConfigs.get("iceberg_minio_port") + sql "drop catalog if exists ${catalog}" + sql """create catalog ${catalog} properties ( + 'type'='iceberg', 'iceberg.catalog.type'='rest', 'uri'='http://${host}:${restPort}', + 's3.access_key'='admin', 's3.secret_key'='password', 's3.region'='us-east-1', + 's3.endpoint'='http://${host}:${s3Port}')""" + try { + sql "create database if not exists ${catalog}.${db}" + sql "use ${catalog}.${db}" + sql "drop table if exists partial_groups" + sql "create table partial_groups (k1 string, k2 string, amount decimal(10,2))" + // Each file spans multiple scan blocks and contains every grouping key. + 4.times { batch -> + sql """insert into partial_groups + select if(number % 2 = 0, 'A', 'B'), if(number % 4 < 2, 'X', 'Y'), + cast(number % 4 + 1 + ${batch} as decimal(10,2)) + from numbers("number" = "32768")""" + } + sql "analyze table partial_groups with sync" + + def query = { forceHash -> """select /*+ SET_VAR(enable_local_shuffle_planner=true, + enable_local_shuffle=true, parallel_pipeline_task_num=4, + enable_external_table_batch_mode=true, num_files_in_batch_mode=1, + disable_streaming_preaggregations=false, enable_bucketed_hash_agg=false, + use_serial_exchange=false, enable_local_exchange_before_streaming_agg=${forceHash}) */ + k1, k2, sum(amount), avg(amount), count(*) from partial_groups + group by k1, k2 order by k1, k2""" } + def expected = [["A", "X", 81920.00G, 2.5000G, 32768L], ["A", "Y", 147456.00G, 4.5000G, 32768L], + ["B", "X", 114688.00G, 3.5000G, 32768L], ["B", "Y", 180224.00G, 5.5000G, 32768L]] + [false, true].each { forceHash -> + def statement = query(forceHash) + def plan = sql("explain distributed plan ${statement}").collect { it[0] }.join("\n") + // Only the immediate child of the partial aggregate determines its distribution. + def exchange = plan =~ /(?m)^\s*\d+:VAGGREGATE \(update serialize\)[^\n]*\n(?:\s*\|[^\n]*\n)*\s*\d+:VLOCAL-EXCHANGE\s*\n\s*\|\s*type: (\w+)/ + assertTrue(exchange.find(), plan) + assertEquals(forceHash ? "LOCAL_EXECUTION_HASH_SHUFFLE" : "PASSTHROUGH", exchange.group(1)) + assertEquals(expected, sql(statement)) + } + } finally { + sql "drop table if exists ${catalog}.${db}.partial_groups" Review Comment: [P3] Preserve the analyzed Iceberg table for debugging If either exchange or result assertion fails, this cleanup removes the table, database, and catalog needed to rerun the failing plan against the same data and statistics. Keep the fixture cleanup before creation, as required by the regression standards in `AGENTS.md`. -- 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]
