This is an automated email from the ASF dual-hosted git repository.

yiguolei pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new 8a6ac8a9777 branch-4.1: [fix](be) Preserve bucket keys in multi-stage 
distinct local shuffle (#70929)
8a6ac8a9777 is described below

commit 8a6ac8a97773aaf575689e4aa5eb1d3554a63abf
Author: Jerry Hu <[email protected]>
AuthorDate: Fri Dec 4 13:56:55 2026 +0800

    branch-4.1: [fix](be) Preserve bucket keys in multi-stage distinct local 
shuffle (#70929)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Problem Summary:
    
    In the BE local-shuffle planner, a colocated aggregation can inherit a
    bucket-distribution requirement without being followed by a shuffled
    operator. Ordinary and distinct-streaming aggregation can then select
    their full grouping keys instead of the input distribution key supplied
    by FE.
    
    For example, when a table is bucketed on `k1` but an aggregation groups
    by `(k1, k2)`, rehashing both columns can produce bucket IDs absent from
    the executing BE's local bucket map. With partial bucket ownership,
    affected multi-stage DISTINCT queries fail with `Rows mismatched` in
    `BUCKET_HASH_SHUFFLE`.
    
    ### What is changed?
    
    - Preserve the first FE input distribution expression list when the
    aggregation is colocated, requires bucket distribution, and that list
    contains a nonempty key.
    - Apply the same selection rule to ordinary and distinct-streaming
    aggregation. Keep existing shuffled-consumer and multi-distinct
    behavior, and safely fall back to grouping expressions when the
    distribution field or outer list is missing or empty. The new bucket-key
    path does not select an empty inner list.
    - Keep actual grouping/deduplication keys, exchange types, bucket
    mappings and row-accounting checks unchanged. No FE, wire-format or
    storage-format changes are needed.
    - Add BE selector coverage and SQL regression coverage for
    three-/four-phase aggregation, streaming and local-shuffle switches,
    automatic phase selection, and duplicate input.
    
    ### Release note
    
    Fix local bucket-routing errors in affected multi-stage DISTINCT
    aggregations.
    
    ### Check List (For Author)
    
    - Test: BE unit tests and SQL regression tests added; local validation
    is listed below.
    - Behavior changed: Yes, affected bucket exchanges retain the input
    bucket key without changing aggregation semantics.
    - Does this need documentation: No.
    
    ### Validation
    
    Completed locally with ASAN BE/FE binaries:
    
    ```bash
    ./build.sh --be --fe -j48
    ./run-be-ut.sh -j 48 --run 
--filter='AggOperatorRequiredDistributionTest.*:DistinctStreamingAggOperatorTest.*:LocalExchangerTest.*:PipelineTest.PLAN_LOCAL_EXCHANGE'
    ```
    
    Build and FE checkstyle passed. All 17 selected BE unit tests passed.
    
    The following regression commands passed. `$REG_CONF` denotes the
    isolated local test-cluster configuration:
    
    ```bash
    ./run-regression-test.sh --conf "$REG_CONF" --run -d query_p0/aggregate -s 
test_bucket_route_multistage_distinct_repro -forceGenOut
    ./run-regression-test.sh --conf "$REG_CONF" --run -d query_p0/aggregate -s 
test_bucket_route_multistage_distinct_repro
    ./run-regression-test.sh --conf "$REG_CONF" --run -d 
pipeline_p0/local_shuffle -s test_bucket_hash_local_shuffle
    ./run-regression-test.sh --conf "$REG_CONF" --run -d nereids_syntax_p0 -s 
agg_4_phase
    ```
    
    The new regression passed repeated non-generation runs, including a
    verification after the final commit. A three-BE validation with partial
    bucket ownership passed all 44 SQL executions. Eight complete, uncached
    profiles retained `BUCKET_HASH_SHUFFLE` with one partition expression,
    while grouping remained on both columns. Formatting and the
    committed-range whitespace check also passed.
    
    Not covered: cloud execution, mixed-version execution, spill, full
    unit/regression suites, or performance benchmarks.
---
 be/src/exec/operator/aggregation_sink_operator.cpp | 12 +++-
 .../distinct_streaming_aggregation_operator.h      | 13 +++-
 be/test/exec/operator/agg_operator_test.cpp        | 61 ++++++++++++++++++
 ...istinct_streaming_aggregation_operator_test.cpp | 61 ++++++++++++++++++
 ...test_bucket_route_multistage_distinct_repro.out | 54 ++++++++++++++++
 ...t_bucket_route_multistage_distinct_repro.groovy | 75 ++++++++++++++++++++++
 6 files changed, 270 insertions(+), 6 deletions(-)

diff --git a/be/src/exec/operator/aggregation_sink_operator.cpp 
b/be/src/exec/operator/aggregation_sink_operator.cpp
index 24edea09950..4bd1329ae05 100644
--- a/be/src/exec/operator/aggregation_sink_operator.cpp
+++ b/be/src/exec/operator/aggregation_sink_operator.cpp
@@ -737,9 +737,15 @@ void AggSinkOperatorX::update_operator(const TPlanNode& 
tnode, bool followed_by_
                                        bool require_bucket_distribution) {
     _followed_by_shuffled_operator = followed_by_shuffled_operator;
     _require_bucket_distribution = require_bucket_distribution;
+    const bool has_fe_distribute_expr_list =
+            tnode.__isset.distribute_expr_lists && 
!tnode.distribute_expr_lists.empty();
+    // A bucket keyed by k1 must not be rehashed by the wider grouping keys 
(k1, k2).
+    const bool use_bucket_key = _is_colocate && _require_bucket_distribution &&
+                                has_fe_distribute_expr_list &&
+                                !tnode.distribute_expr_lists.front().empty();
     _partition_exprs =
-            tnode.__isset.distribute_expr_lists &&
-                            (_followed_by_shuffled_operator ||
+            has_fe_distribute_expr_list &&
+                            (_followed_by_shuffled_operator || use_bucket_key 
||
                              std::any_of(
                                      
tnode.agg_node.aggregate_functions.begin(),
                                      tnode.agg_node.aggregate_functions.end(),
@@ -747,7 +753,7 @@ void AggSinkOperatorX::update_operator(const TPlanNode& 
tnode, bool followed_by_
                                          return 
texpr.nodes[0].fn.name.function_name.starts_with(
                                                  DISTINCT_FUNCTION_PREFIX);
                                      }))
-                    ? tnode.distribute_expr_lists[0]
+                    ? tnode.distribute_expr_lists.front()
                     : tnode.agg_node.grouping_exprs;
 }
 
diff --git a/be/src/exec/operator/distinct_streaming_aggregation_operator.h 
b/be/src/exec/operator/distinct_streaming_aggregation_operator.h
index 6aecaa209f6..f99d648ddec 100644
--- a/be/src/exec/operator/distinct_streaming_aggregation_operator.h
+++ b/be/src/exec/operator/distinct_streaming_aggregation_operator.h
@@ -105,9 +105,16 @@ public:
                          bool require_bucket_distribution) override {
         _followed_by_shuffled_operator = followed_by_shuffled_operator;
         _require_bucket_distribution = require_bucket_distribution;
-        _partition_exprs = tnode.__isset.distribute_expr_lists && 
_followed_by_shuffled_operator
-                                   ? tnode.distribute_expr_lists[0]
-                                   : tnode.agg_node.grouping_exprs;
+        const bool has_fe_distribute_expr_list =
+                tnode.__isset.distribute_expr_lists && 
!tnode.distribute_expr_lists.empty();
+        // A bucket keyed by k1 must not be rehashed by the wider grouping 
keys (k1, k2).
+        const bool use_bucket_key = _is_colocate && 
_require_bucket_distribution &&
+                                    has_fe_distribute_expr_list &&
+                                    
!tnode.distribute_expr_lists.front().empty();
+        _partition_exprs =
+                has_fe_distribute_expr_list && (_followed_by_shuffled_operator 
|| use_bucket_key)
+                        ? tnode.distribute_expr_lists.front()
+                        : tnode.agg_node.grouping_exprs;
     }
     Status prepare(RuntimeState* state) override;
     Status pull(RuntimeState* state, Block* block, bool* eos) const override;
diff --git a/be/test/exec/operator/agg_operator_test.cpp 
b/be/test/exec/operator/agg_operator_test.cpp
index 1934de3b59f..df6a8884036 100644
--- a/be/test/exec/operator/agg_operator_test.cpp
+++ b/be/test/exec/operator/agg_operator_test.cpp
@@ -19,6 +19,7 @@
 #include <gtest/gtest.h>
 
 #include <memory>
+#include <vector>
 
 #include "core/data_type/data_type_nullable.h"
 #include "core/data_type/data_type_number.h"
@@ -32,6 +33,7 @@
 #include "exec/pipeline/pipeline.h"
 #include "testutil/column_helper.h"
 #include "testutil/mock/mock_agg_fn_evaluator.h"
+#include "testutil/mock/mock_descriptors.h"
 #include "testutil/mock/mock_slot_ref.h"
 
 namespace doris {
@@ -121,6 +123,65 @@ std::shared_ptr<AggSinkOperatorX> 
create_agg_sink_op(OperatorContext& ctx, bool
     return op;
 }
 
+TEST(AggOperatorRequiredDistributionTest, 
retain_distribute_key_for_bucket_child) {
+    OperatorContext ctx;
+    TQueryOptions query_options;
+    query_options.__set_enable_local_exchange_before_agg(true);
+    ctx.state.set_query_options(query_options);
+    auto slot_expr = [](int slot_id) {
+        TExpr expr;
+        auto& node = expr.nodes.emplace_back();
+        node.node_type = TExprNodeType::SLOT_REF;
+        node.slot_ref.__set_slot_id(slot_id);
+        node.slot_ref.__set_tuple_id(0);
+        return expr;
+    };
+    const auto k1 = slot_expr(1);
+    const auto k2 = slot_expr(2);
+    MockDescriptorTbl descs {{std::make_shared<DataTypeInt64>(), 
std::make_shared<DataTypeInt64>()},
+                             &ctx.pool};
+    TPlanNode plan;
+    plan.row_tuples = {0};
+    plan.nullable_tuples = {false};
+    plan.agg_node.__set_is_colocate(true);
+    plan.agg_node.need_finalize = true;
+    plan.agg_node.grouping_exprs = {k1, k2};
+    plan.__set_distribute_expr_lists({{k1}});
+
+    auto check = [&](auto& candidate, bool followed, bool bucket, ExchangeType 
type,
+                     const std::vector<int>& slots) {
+        candidate.update_operator(plan, followed, bucket);
+        const auto distribution = 
candidate.required_data_distribution(&ctx.state);
+        EXPECT_EQ(type, distribution.distribution_type);
+        ASSERT_EQ(slots.size(), distribution.partition_exprs.size());
+        for (size_t i = 0; i < slots.size(); ++i) {
+            ASSERT_EQ(1, distribution.partition_exprs[i].nodes.size());
+            EXPECT_EQ(TExprNodeType::SLOT_REF, 
distribution.partition_exprs[i].nodes[0].node_type);
+            EXPECT_EQ(slots[i], 
distribution.partition_exprs[i].nodes[0].slot_ref.slot_id);
+        }
+        ASSERT_EQ(2, plan.agg_node.grouping_exprs.size());
+        EXPECT_EQ(1, 
plan.agg_node.grouping_exprs[0].nodes[0].slot_ref.slot_id);
+        EXPECT_EQ(2, 
plan.agg_node.grouping_exprs[1].nodes[0].slot_ref.slot_id);
+    };
+    AggSinkOperatorX child(&ctx.pool, 2, 2, plan, descs);
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1});
+    check(child, false, false, ExchangeType::HASH_SHUFFLE, {1, 2});
+    check(child, true, false, ExchangeType::HASH_SHUFFLE, {1});
+
+    plan.__isset.distribute_expr_lists = false;
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1, 2});
+    plan.__set_distribute_expr_lists({});
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1, 2});
+    plan.__set_distribute_expr_lists({{}});
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1, 2});
+
+    plan.__set_distribute_expr_lists({{k1}});
+    plan.agg_node.__set_is_colocate(false);
+    AggSinkOperatorX non_colocate(&ctx.pool, 3, 3, plan, descs);
+    check(non_colocate, false, true, ExchangeType::HASH_SHUFFLE, {1, 2});
+    check(non_colocate, true, true, ExchangeType::HASH_SHUFFLE, {1});
+}
+
 TEST(AggOperatorRequiredDistributionTest, 
require_hash_shuffle_after_non_hash_child_exchange) {
     OperatorContext ctx;
     TQueryOptions query_options;
diff --git 
a/be/test/exec/operator/distinct_streaming_aggregation_operator_test.cpp 
b/be/test/exec/operator/distinct_streaming_aggregation_operator_test.cpp
index 17282356625..ea6509c3637 100644
--- a/be/test/exec/operator/distinct_streaming_aggregation_operator_test.cpp
+++ b/be/test/exec/operator/distinct_streaming_aggregation_operator_test.cpp
@@ -20,6 +20,7 @@
 #include <gtest/gtest.h>
 
 #include <memory>
+#include <vector>
 
 #include "core/block/block.h"
 #include "exec/exchange/local_exchange_source_operator.h"
@@ -78,6 +79,66 @@ struct DistinctStreamingAggOperatorTest : public 
::testing::Test {
     ObjectPool pool;
 };
 
+TEST_F(DistinctStreamingAggOperatorTest, 
bucket_parent_preserves_distribute_key) {
+    TQueryOptions query_options;
+    query_options.__set_enable_local_exchange_before_agg(true);
+    state->set_query_options(query_options);
+    auto slot_expr = [](int slot_id) {
+        TExpr expr;
+        auto& node = expr.nodes.emplace_back();
+        node.node_type = TExprNodeType::SLOT_REF;
+        node.slot_ref.__set_slot_id(slot_id);
+        node.slot_ref.__set_tuple_id(0);
+        return expr;
+    };
+    const auto k1 = slot_expr(1);
+    const auto k2 = slot_expr(2);
+    MockDescriptorTbl descs {{std::make_shared<DataTypeInt64>(), 
std::make_shared<DataTypeInt64>()},
+                             &pool};
+    TPlanNode plan;
+    plan.row_tuples = {0};
+    plan.nullable_tuples = {false};
+    plan.agg_node.__set_is_colocate(true);
+    plan.agg_node.need_finalize = true;
+    plan.agg_node.grouping_exprs = {k1, k2};
+    plan.__set_distribute_expr_lists({{k1}});
+
+    auto check = [&](auto& candidate, bool followed, bool bucket, ExchangeType 
type,
+                     const std::vector<int>& slots) {
+        candidate._probe_expr_ctxs = MockSlotRef::create_mock_contexts(
+                {std::make_shared<DataTypeInt64>(), 
std::make_shared<DataTypeInt64>()});
+        candidate.update_operator(plan, followed, bucket);
+        const auto distribution = 
candidate.required_data_distribution(state.get());
+        EXPECT_EQ(type, distribution.distribution_type);
+        ASSERT_EQ(slots.size(), distribution.partition_exprs.size());
+        for (size_t i = 0; i < slots.size(); ++i) {
+            ASSERT_EQ(1, distribution.partition_exprs[i].nodes.size());
+            EXPECT_EQ(TExprNodeType::SLOT_REF, 
distribution.partition_exprs[i].nodes[0].node_type);
+            EXPECT_EQ(slots[i], 
distribution.partition_exprs[i].nodes[0].slot_ref.slot_id);
+        }
+        ASSERT_EQ(2, plan.agg_node.grouping_exprs.size());
+        EXPECT_EQ(1, 
plan.agg_node.grouping_exprs[0].nodes[0].slot_ref.slot_id);
+        EXPECT_EQ(2, 
plan.agg_node.grouping_exprs[1].nodes[0].slot_ref.slot_id);
+    };
+    DistinctStreamingAggOperatorX child(&pool, 2, plan, descs);
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1});
+    check(child, false, false, ExchangeType::HASH_SHUFFLE, {1, 2});
+    check(child, true, false, ExchangeType::HASH_SHUFFLE, {1});
+
+    plan.__isset.distribute_expr_lists = false;
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1, 2});
+    plan.__set_distribute_expr_lists({});
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1, 2});
+    plan.__set_distribute_expr_lists({{}});
+    check(child, false, true, ExchangeType::BUCKET_HASH_SHUFFLE, {1, 2});
+
+    plan.__set_distribute_expr_lists({{k1}});
+    plan.agg_node.__set_is_colocate(false);
+    DistinctStreamingAggOperatorX non_colocate(&pool, 3, plan, descs);
+    check(non_colocate, false, true, ExchangeType::HASH_SHUFFLE, {1, 2});
+    check(non_colocate, true, true, ExchangeType::HASH_SHUFFLE, {1});
+}
+
 TEST_F(DistinctStreamingAggOperatorTest, test1) {
     op->_is_streaming_preagg = false;
 
diff --git 
a/regression-test/data/query_p0/aggregate/test_bucket_route_multistage_distinct_repro.out
 
b/regression-test/data/query_p0/aggregate/test_bucket_route_multistage_distinct_repro.out
new file mode 100644
index 00000000000..3d47694c135
--- /dev/null
+++ 
b/regression-test/data/query_p0/aggregate/test_bucket_route_multistage_distinct_repro.out
@@ -0,0 +1,54 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !unique_keys_phase3_streamtrue_shuffletrue --
+128    128
+
+-- !unique_keys_phase3_streamtrue_shufflefalse --
+128    128
+
+-- !unique_keys_phase4_streamtrue_shuffletrue --
+128    128
+
+-- !unique_keys_phase4_streamtrue_shufflefalse --
+128    128
+
+-- !unique_keys_phase3_streamfalse_shuffletrue --
+128    128
+
+-- !unique_keys_phase3_streamfalse_shufflefalse --
+128    128
+
+-- !unique_keys_phase4_streamfalse_shuffletrue --
+128    128
+
+-- !unique_keys_phase4_streamfalse_shufflefalse --
+128    128
+
+-- !unique_keys_automatic_phase --
+128    128
+
+-- !multiple_values_phase3_streamtrue_shuffletrue --
+128    256
+
+-- !multiple_values_phase3_streamtrue_shufflefalse --
+128    256
+
+-- !multiple_values_phase4_streamtrue_shuffletrue --
+128    256
+
+-- !multiple_values_phase4_streamtrue_shufflefalse --
+128    256
+
+-- !multiple_values_phase3_streamfalse_shuffletrue --
+128    256
+
+-- !multiple_values_phase3_streamfalse_shufflefalse --
+128    256
+
+-- !multiple_values_phase4_streamfalse_shuffletrue --
+128    256
+
+-- !multiple_values_phase4_streamfalse_shufflefalse --
+128    256
+
+-- !multiple_values_automatic_phase --
+128    256
diff --git 
a/regression-test/suites/query_p0/aggregate/test_bucket_route_multistage_distinct_repro.groovy
 
b/regression-test/suites/query_p0/aggregate/test_bucket_route_multistage_distinct_repro.groovy
new file mode 100644
index 00000000000..f8db8382e63
--- /dev/null
+++ 
b/regression-test/suites/query_p0/aggregate/test_bucket_route_multistage_distinct_repro.groovy
@@ -0,0 +1,75 @@
+// 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_bucket_route_multistage_distinct_repro", "p0") {
+    def tableName = "bucket_route_multistage_distinct_repro"
+    sql "DROP TABLE IF EXISTS ${tableName}"
+    sql """
+        CREATE TABLE ${tableName} (
+            k1 VARCHAR(32) NOT NULL,
+            k2 INT NOT NULL
+        ) DUPLICATE KEY(k1)
+        DISTRIBUTED BY HASH(k1) BUCKETS 3
+        PROPERTIES ('replication_num'='1')
+    """
+    sql """
+        INSERT INTO ${tableName}
+        SELECT concat('key_', cast(number AS VARCHAR)), cast(number % 7 AS INT)
+        FROM numbers('number'='128')
+    """
+    sql "SET enable_sql_cache=false"
+    sql "SET enable_query_cache=false"
+    sql "SET parallel_pipeline_task_num=8"
+    sql "SET ignore_storage_data_distribution=true"
+    sql "SET enable_local_exchange_before_agg=true"
+    sql "SET enable_spill=false"
+
+    def query = """
+        SELECT COUNT(DISTINCT k1), COUNT(k1)
+        FROM (SELECT DISTINCT k1, k2 FROM ${tableName}) s
+    """
+    def checkMatrix = { shape ->
+        for (def streaming : [true, false]) {
+            sql "SET enable_distinct_streaming_aggregation=${streaming}"
+            for (def phase : [3, 4]) {
+                sql "SET agg_phase=${phase}"
+                for (def shuffle : [true, false]) {
+                    sql "SET experimental_enable_local_shuffle=${shuffle}"
+                    
"order_qt_${shape}_phase${phase}_stream${streaming}_shuffle${shuffle}"(query)
+                }
+            }
+        }
+        sql "SET enable_distinct_streaming_aggregation=true"
+        sql "SET experimental_enable_local_shuffle=true"
+        sql "SET agg_phase=0"
+        "order_qt_${shape}_automatic_phase"(query)
+    }
+
+    checkMatrix("unique_keys")
+    sql """
+        INSERT INTO ${tableName}
+        SELECT concat('key_', cast(number AS VARCHAR)), cast(number % 7 + 7 AS 
INT)
+        FROM numbers('number'='128')
+    """
+    sql """
+        INSERT INTO ${tableName}
+        SELECT concat('key_', cast(number AS VARCHAR)), cast(number % 7 AS INT)
+        FROM numbers('number'='128')
+    """
+    checkMatrix("multiple_values")
+    sql "DROP TABLE ${tableName}"
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to