hello-stephen commented on code in PR #71331:
URL: https://github.com/apache/doris/pull/71331#discussion_r4799999989


##########
fe/fe-core/src/main/java/org/apache/doris/planner/AddLocalExchange.java:
##########
@@ -81,20 +89,67 @@ 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<PlanFragment.AdaptiveDecimalBackend> oneCapableBackend = 
Suppliers.memoize(
+                () -> getAdaptiveDecimalBackend(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();
+            PlanNode root = fragment.getPlanRoot();
+            context.setBlockAggregationEligible(root instanceof AggregationNode
+                    && jobs.size() == AggregationNode.BLOCK_AGGREGATION_TASKS
+                    && oneCapableBackend.get() != null);
             context.setCurrentFragmentBucketUpgradeEligible(
                     isBucketUpgradeEligible(pipePlan, maxPerBeInstances, 
context));
-            PlanFragment fragment = pipePlan.getFragmentJob().getFragment();
             addLocalExchangeForFragment(fragment, context);
+            if (context.isBlockAggregationEligible() && ((AggregationNode) 
root).usesAdaptiveDecimalStates()) {
+                fragment.setAdaptiveDecimalBackend(oneCapableBackend.get());
+            }
+        }
+    }
+
+    private static PlanFragment.AdaptiveDecimalBackend 
getAdaptiveDecimalBackend(
+            FragmentIdMapping<DistributedPlan> plans, ConnectContext connect) {
+        if (connect == null || connect.getEnv() == null || 
!connect.getEnv().isMaster()) {
+            return null;
+        }
+        // Fragment ids are ordered bottom-up, as in CoordinatorContext. Only 
client result
+        // queries can use this optimization. An intermediate stream also 
feeds writes and OUTFILE.
+        if 
(!(plans.lastEntry().getValue().getFragmentJob().getFragment().getSink() 
instanceof ResultSink)
+                || !connect.getProtocolAdapter().canRetryQuery(connect)) {

Review Comment:
   [P2] Require an available replan before selecting private states
   
   For MySQL, `canRetryQuery` only checks whether the channel has sent output. 
With the supported `max_query_retry_time=0`, an eligible Decimal128 query can 
choose the private functions and enter the workload queue. If a transient 
heartbeat failure revokes the capability while the same BE still serves BRPC, 
`Coordinator.exec` rejects the plan after admission. 
`StmtExecutor.executeWithReplanRetries` immediately rethrows on the only 
attempt, even though the ordinary hash plan could execute on that worker.
   
   Keep the ordinary plan when the current execution has no fallback attempt 
available. See `MysqlProtocolAdapter.java:143`, `Backend.java:929`, and 
`StmtExecutor.java:719–743`.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java:
##########
@@ -1314,6 +1321,17 @@ 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);

Review Comment:
   [P2] Use snapshot-aligned statistics for the grouping estimate
   
   An unqualified Iceberg query can pin a new snapshot after an external writer 
replaces or appends data while Doris still has the old `ANALYZE` NDVs. Both 
grouping columns can still report NDV 2 here when the pinned snapshot contains 
10,000 repeated key pairs. The row-count threshold can use the new row count 
while the old key estimates admit the following plan.
   
   ```text
   Final merge by (k1, k2)
     Hash fragment exchange (k1, k2)
       Streaming partial aggregate by (k1, k2)
         Local PASSTHROUGH
           Serial Iceberg scan of the current snapshot
   ```
   
   If repeated scan blocks feed all four tasks and preaggregation stays active, 
this can emit 40,000 states where local hash already keeps all four local tasks 
busy and emits 10,000. For two 4 KiB keys that is about 313 MiB of raw key 
payload instead of 78 MiB, before state overhead and compression. The 
explicit-selector guard does not catch this ordinary current-snapshot scan. 
Check that the key statistics describe the pinned data before enabling 
passthrough. `StatsCalculator.java:1464–1476` reuses table/column NDVs, and 
`ColumnStatisticsCacheLoader.java:37–65` loads the persisted analysis first.



##########
regression-test/suites/external_table_p0/iceberg/test_iceberg_low_cardinality_partial_agg.groovy:
##########
@@ -0,0 +1,166 @@
+// 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
+    }
+
+    // Only the master FE has a directly observed backend capability heartbeat.
+    context.reconnectToMasterFe()
+    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}')"""
+    sql "create database if not exists ${catalog}.${db}"
+    sql "use ${catalog}.${db}"
+    // One writer produces a single Parquet row group. Eager split planning 
assigns it to one worker,
+    // including on multi-BE clusters. Batch planning uses all available scan 
workers.
+    def populate = { int rowsPerGroup ->
+        sql "drop table if exists partial_groups"
+        sql "create table partial_groups (k1 string, k2 string, amount 
decimal(10,2), row_no int)"
+        sql """insert into partial_groups
+            select /*+ SET_VAR(parallel_pipeline_task_num=1) */
+                   if(number % 2 = 0, 'A', 'B'), if(number % 4 < 2, 'X', 'Y'),
+                   cast(number % 4 - 3 + (number div ${rowsPerGroup}) as 
decimal(10,2)),
+                   number % ${rowsPerGroup}
+            from numbers("number" = "${4L * rowsPerGroup}")"""
+        sql "analyze table partial_groups with sync"
+    }
+    def query = { aggregates, forceHash, predicate = "", batch = false -> 
"""select /*+ SET_VAR(enable_local_shuffle_planner=true,
+            enable_local_shuffle=true, enable_decimal256=false, 
parallel_pipeline_task_num=4,
+            enable_external_table_batch_mode=${batch}, 
num_files_in_batch_mode=1, file_split_size=268435456, max_file_split_num=1,
+            disable_streaming_preaggregations=false, 
enable_bucketed_hash_agg=false,
+            use_serial_exchange=false, 
enable_local_exchange_before_streaming_agg=${forceHash}) */
+            k1, k2, ${aggregates}, count(*) from partial_groups ${predicate}
+            group by k1, k2 order by k1, k2""" }
+
+    def hash = "LOCAL_EXECUTION_HASH_SHUFFLE"
+    def passthrough = "PASSTHROUGH"
+    def inspectPlan = { statement ->
+        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)
+        def worker = ~/worker: BackendWorker\(id: (\d+)/
+        def scanJobs = plan.split(/PipelineDistributedPlan\(/).find {
+            it.contains("fragmentJob: UnassignedScanSingleRemoteTableJob")
+        }
+        assertNotNull(scanJobs, plan)
+        def scanAssignments = (scanJobs =~ worker).collect { it[1] }
+        [type: exchange.group(1), states: plan.readLines().count { 
it.contains("adaptive decimal state:") },
+         workers: (plan =~ worker).collect { it[1] }.toSet(),
+         scanWorkers: scanAssignments.toSet(), tasks: scanAssignments.size()]
+    }
+    def checkPlan = { observed, expected ->
+        assertEquals(expected, observed.type, observed.toString())
+        assertEquals(expected == passthrough ? 2 : 0, observed.states, 
observed.toString())
+    }
+    // The External CI fixture runs a matching FE/BE build. Upgrade fixtures 
can pin legacy
+    // explicitly. An unspecified fixture checks compatibility without 
claiming positive coverage.
+    def fixture = context.config.otherConfigs.get("icebergPartialAggBackend") 
?: "unspecified"
+    assertTrue(fixture in ["current", "legacy", "unspecified"])
+    def checkDecimal = { statement ->
+        def observed = inspectPlan(statement)
+        if (fixture == "current") {
+            // FE processes the disk report and the capability heartbeat 
independently.
+            // A matching fixture must eventually select the dedicated states 
or fail the suite.
+            if (observed.type == hash) {
+                awaitUntil(90) {
+                    checkPlan(observed, hash)
+                    observed = inspectPlan(statement)
+                    observed.type != hash
+                }
+            }
+            checkPlan(observed, passthrough)
+        } else if (fixture == "legacy" || observed.type == hash) {
+            checkPlan(observed, hash)
+        } else {
+            checkPlan(observed, passthrough)
+        }
+        if (fixture != "unspecified" || observed.type == passthrough) {
+            assertEquals(1, observed.workers.size(), observed.toString())
+            assertEquals(4, observed.tasks, observed.toString())
+        }
+        logger.info("Iceberg Decimal fixture=${fixture}, plan=${observed}")
+    }
+
+    def wholeDecimalSum = "sum(cast(amount as decimal(10,0)))"
+    populate(8192)
+    def small = query(wholeDecimalSum, false)
+    checkPlan(inspectPlan(small), hash)
+    qt_small small
+
+    populate(524288)
+    def selective = query(wholeDecimalSum, false, "where row_no < 8")
+    checkPlan(inspectPlan(selective), hash)
+    qt_selective selective
+
+    // A narrow decimal input also needs a safe Decimal128 subtotal when 
blocks fan out.
+    def decimalSum = query("sum(amount)", false)
+    checkDecimal(decimalSum)
+    qt_decimal_sum decimalSum
+
+    def decimalAvg = query("avg(amount)", false)

Review Comment:
   [P3] Exercise a promoted subtotal through the fragment exchange
   
   The current fixture proves that both stages select the private functions, 
but even its largest possible subtotal is far below the Int128 limit. The 
signed promotion unit test exercises direct factory serialization, so a 
regression specific to moving a promoted state through the SQL fragment 
exchange would escape this suite.
   
   Add a current-worker AVG case with repeated exact `DECIMAL(38,4)` values of 
magnitude 9 × 10³³. Two values in a task exceed Int128 at that scale, while 
their exact average still fits the SQL result type. Assert the passthrough plan 
and record the exact average in the generated output.



-- 
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]

Reply via email to