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


##########
be/src/exec/operator/groupjoin_probe_operator.cpp:
##########
@@ -0,0 +1,529 @@
+// 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.
+
+#include "exec/operator/groupjoin_probe_operator.h"
+
+#include <algorithm>
+#include <set>
+
+#include "core/column/column_nullable.h"
+#include "exec/common/hash_table/hash_map_util.h"
+#include "exec/common/hash_table/join_hash_table_utils.h"
+#include "exec/common/join_utils.h"
+#include "exec/common/template_helpers.hpp"
+#include "exec/common/util.hpp"
+#include "exec/operator/groupjoin_operator_utils.h"
+#include "exprs/vectorized_agg_fn.h"
+#include "exprs/vexpr.h"
+#include "runtime/descriptors.h"
+#include "runtime/runtime_state.h"
+
+namespace doris {
+GroupJoinProbeLocalState::GroupJoinProbeLocalState(RuntimeState* state, 
OperatorXBase* parent)
+        : Base(state, parent) {}
+GroupJoinProbeLocalState::~GroupJoinProbeLocalState() = default;
+Status GroupJoinProbeLocalState::init(RuntimeState* state, LocalStateInfo& 
info) {
+    RETURN_IF_ERROR(Base::init(state, info));
+    auto& parent = _parent->cast<GroupJoinProbeOperatorX>();
+    for (const auto& expr : parent._key_exprs) {
+        VExprContextSPtr clone;
+        RETURN_IF_ERROR(expr->clone(state, clone));
+        _key_exprs.push_back(std::move(clone));
+    }
+    for (auto* evaluator : parent._evaluators) {
+        _evaluators.push_back(evaluator->clone(state, parent._pool));
+    }
+    _match_timer = ADD_TIMER(custom_profile(), "ProbeMatchTime");
+    _update_timer = ADD_TIMER(custom_profile(), "AggregateUpdateTime");
+    _drain_timer = ADD_TIMER(custom_profile(), "ResultDrainTime");
+    _matched_rows = ADD_COUNTER(custom_profile(), "MatchedRows", TUnit::UNIT);
+    _group_count = ADD_COUNTER(custom_profile(), "MatchedGroups", TUnit::UNIT);
+    return Status::OK();
+}
+
+Status GroupJoinProbeLocalState::close(RuntimeState* state) {
+    if (_closed) {
+        return Status::OK();
+    }
+    auto& parent = _parent->cast<GroupJoinProbeOperatorX>();
+    for (size_t group_id = 0; group_id < _group_build_rows.size(); ++group_id) 
{
+        auto* const place = _group_states[group_id];
+        for (size_t i = 0; i < _evaluators.size(); ++i) {
+            _evaluators[i]->destroy(place + parent._offsets[i]);
+        }
+    }
+    decltype(_group_build_rows) {}.swap(_group_build_rows);
+    decltype(_state_by_build_row) {}.swap(_state_by_build_row);
+    decltype(_group_states) {}.swap(_group_states);
+    decltype(_result_places) {}.swap(_result_places);
+    _release_probe_resources();
+    _arena.clear(true);
+    COUNTER_SET(_memory_used_counter, 0);
+    return Base::close(state);
+}
+
+void GroupJoinProbeLocalState::_release_probe_resources() {
+    _argument_columns.clear();
+    _probe_arguments.clear();
+    _build_arguments.clear();
+    _probe_context.reset();
+    decltype(_match_places) {}.swap(_match_places);
+    decltype(_match_build_rows) {}.swap(_match_build_rows);
+    decltype(_match_probe_rows) {}.swap(_match_probe_rows);
+    _child_block->clear();
+}
+
+void GroupJoinProbeLocalState::_update_memory_usage() {
+    // Structural buffers only: shared build columns and aggregate-owned heap 
allocations
+    // are not included here. Query memory enforcement uses the task's 
MemTracker.
+    size_t probe_key_bytes = 0;
+    if (_probe_context) {
+        probe_key_bytes =
+                std::visit(Overload {[](std::monostate&) -> size_t { return 0; 
},
+                                     [](auto& method) {
+                                         return 
method.serialized_keys_size(false) +
+                                                method.bucket_nums.capacity() 
* sizeof(uint32_t);
+                                     }},
+                           _probe_context->method_variant);
+    }
+    COUNTER_SET(_memory_used_counter,
+                _arena.size() + _state_by_build_row.capacity() * 
sizeof(AggregateDataPtr) +
+                        _group_states.capacity() * sizeof(AggregateDataPtr) +
+                        _result_places.capacity() * sizeof(AggregateDataPtr) + 
probe_key_bytes +
+                        _group_build_rows.capacity() * sizeof(uint32_t) +
+                        _match_places.capacity() * sizeof(AggregateDataPtr) +
+                        (_match_build_rows.capacity() + 
_match_probe_rows.capacity()) *
+                                sizeof(uint32_t));
+}
+
+GroupJoinProbeOperatorX::GroupJoinProbeOperatorX(ObjectPool* pool, const 
TPlanNode& node,
+                                                 int operator_id, const 
DescriptorTbl& descs)
+        : Base(pool, node, operator_id, descs),
+          _output_tuple_id(node.group_join_node.output_tuple_id),
+          _distribution(node.group_join_node.dist_type),
+          _partition_exprs(node.__isset.distribute_expr_lists ? 
node.distribute_expr_lists[0]
+                                                              : 
std::vector<TExpr> {}) {
+    _op_name = "GROUP_JOIN_OPERATOR";
+    _row_descriptor = RowDescriptor(descs, std::vector<TupleId> 
{_output_tuple_id});
+}
+
+Status GroupJoinProbeOperatorX::init(const TPlanNode& node, RuntimeState* 
state) {
+    RETURN_IF_ERROR(Base::init(node, state));
+    RETURN_IF_ERROR(groupjoin::validate_group_join_node(node));
+    for (const auto& conjunct : node.group_join_node.eq_join_conjuncts) {
+        VExprContextSPtr expr;
+        RETURN_IF_ERROR(VExpr::create_expr_tree(conjunct.left, expr));
+        _key_exprs.push_back(std::move(expr));
+    }
+    TSortInfo sort_info;
+    for (const auto& aggregate : node.group_join_node.aggregate_functions) {
+        AggFnEvaluator* evaluator = nullptr;
+        RETURN_IF_ERROR(AggFnEvaluator::create(_pool, 
aggregate.aggregate_function, sort_info,
+                                               false, false, &evaluator));
+        if (evaluator->is_merge()) {
+            return Status::InternalError("GroupJoin requires input-to-result 
aggregates");
+        }
+        _has_joined_arguments |= aggregate.input_side == 
TGroupJoinAggSide::JOINED;
+        _evaluators.push_back(evaluator);
+        _sides.push_back(aggregate.input_side);
+    }
+    return Status::OK();
+}
+
+Status GroupJoinProbeOperatorX::prepare(RuntimeState* state) {
+    RETURN_IF_ERROR(Base::prepare(state));
+    for (const auto& expr : _key_exprs) {
+        RETURN_IF_ERROR(expr->prepare(state, 
_child->operator_row_desc_after_projection()));
+        RETURN_IF_ERROR(expr->open(state));
+    }
+    _joined_row_desc = 
RowDescriptor(_child->operator_row_desc_after_projection(),
+                                     
_build_side_child->operator_row_desc_after_projection());
+    _joined_columns.assign(_joined_row_desc.num_slots(), 0);
+    for (size_t i = 0; i < _evaluators.size(); ++i) {
+        RETURN_IF_ERROR(_prepare_evaluator(state, i));
+    }
+    _states_size = (_states_size + _states_alignment - 1) / _states_alignment 
* _states_alignment;
+    return Status::OK();
+}
+
+Status GroupJoinProbeOperatorX::_prepare_evaluator(RuntimeState* state, size_t 
index) {
+    const auto& input =
+            _sides[index] == TGroupJoinAggSide::JOINED
+                    ? _joined_row_desc
+                    : (_sides[index] == TGroupJoinAggSide::BUILD ? 
_build_side_child : _child)
+                              ->operator_row_desc_after_projection();
+    auto* output = state->desc_tbl().get_tuple_descriptor(_output_tuple_id);
+    auto* slot = output->slots()[_key_exprs.size() + index];
+    auto* evaluator = _evaluators[index];
+    RETURN_IF_ERROR(evaluator->prepare(state, input, slot, slot));
+    evaluator->set_version(state->be_exec_version());
+    RETURN_IF_ERROR(evaluator->open(state));
+    if (_sides[index] == TGroupJoinAggSide::JOINED) {
+        std::set<int> columns;
+        for (const auto& expr : evaluator->input_exprs_ctxs()) {
+            expr->root()->collect_slot_column_ids(columns);
+        }
+        for (const auto column : columns) {
+            DCHECK_GE(column, 0);
+            DCHECK_LT(static_cast<size_t>(column), _joined_columns.size());
+            _joined_columns[column] = 1;
+        }
+    }
+    const auto alignment = evaluator->align_of_data();
+    _states_alignment = std::max(_states_alignment, alignment);
+    _states_size = (_states_size + alignment - 1) / alignment * alignment;
+    _offsets.push_back(_states_size);
+    _states_size += evaluator->size_of_data();
+    return Status::OK();
+}
+
+AggregateDataPtr 
GroupJoinProbeOperatorX::_create_group_state(GroupJoinProbeLocalState& local,
+                                                              uint32_t head) 
const {
+    const auto group_count_before_create = local._group_build_rows.size();
+    auto* data = local._arena.aligned_alloc(_states_size, _states_alignment);
+    size_t constructed = 0;
+    try {
+        for (; constructed < local._evaluators.size(); ++constructed) {
+            local._evaluators[constructed]->create(data + 
_offsets[constructed]);
+        }
+        // Register only fully constructed states so close() can destroy them 
after any error.
+        local._group_build_rows.push_back(head);
+        local._group_states.push_back(data);
+    } catch (...) {
+        if (local._group_states.size() > local._group_build_rows.size()) {
+            local._group_states.pop_back();
+        }
+        if (local._group_build_rows.size() > group_count_before_create) {
+            local._group_build_rows.pop_back();
+        }
+        for (size_t i = 0; i < constructed; ++i) {
+            local._evaluators[i]->destroy(data + _offsets[i]);
+        }
+        throw;
+    }
+    local._state_by_build_row[head] = data;
+    return data;
+}
+
+Status GroupJoinProbeOperatorX::_initialize_probe(GroupJoinProbeLocalState& 
local) const {
+    const auto& shared = *local._shared_state;
+    local._state_by_build_row.assign(shared.build_block.rows(), nullptr);
+    local._probe_context = make_join_probe_context(*shared.build_context);
+    local._build_arguments.resize(_evaluators.size());
+    local._probe_arguments.resize(_evaluators.size());
+    local._argument_columns.resize(_evaluators.size());
+    // Share source columns, but keep expression result slots private to this 
probe.
+    Block build_expressions = shared.build_block;
+    for (size_t i = 0; i < _evaluators.size(); ++i) {
+        if (_sides[i] != TGroupJoinAggSide::BUILD) {
+            continue;
+        }
+        for (const auto& expr : local._evaluators[i]->input_exprs_ctxs()) {
+            ColumnPtr argument;
+            RETURN_IF_ERROR(groupjoin::evaluate_column(build_expressions, 
expr, argument));

Review Comment:
   [P1] Evaluate side-only aggregate arguments only on matched rows
   
   With fusion, one-phase aggregation, and `enable_strict_cast=true`, this 
admitted plan fails on an unmatched build row:
   
   ```text
   Aggregate[a.k, SUM(CAST(b.v AS INT))]
     InnerHashJoin[a.k = b.k, SHUFFLE]
       a: (1)
       b: (1, '7'), (2, 'bad')
   ```
   
   `_initialize_probe` evaluates the cast over the whole build block here, so 
`'bad'` raises an error; ordinary HashJoin + Aggregate discards key 2 before 
evaluating the cast and returns `(1, 7)`. `NormalizeAggregate` keeps an 
ordinary non-DISTINCT cast inside the aggregate, and deterministic `Cast` 
passes the current volatile/NoneMovable gate. `_prepare_probe` has the same 
issue for PROBE arguments. Evaluate potentially throwing arguments on matched 
rows/pairs, or exclude those expressions from fusion, and cover this case with 
RF disabled.



##########
gensrc/thrift/PlanNodes.thrift:
##########
@@ -1656,6 +1657,60 @@ struct TAggregationNode {
   10: optional TSortInfo agg_sort_info_by_group_key
 }
 
+enum TGroupJoinAggSide {
+  BUILD = 0,
+  PROBE = 1,
+  // Evaluate arguments over each matched row pair.
+  JOINED = 2,
+}
+
+enum TGroupJoinAggOutputMode {
+  // 直接输出最终聚合结果。这是 GroupJoin 的主路径:
+  // hash join 已经按照 join/group key 做过数据分布,所以不需要下游 global agg merge。
+  // Only FINAL_RESULT is supported by the current executor.
+  FINAL_RESULT = 0,
+  // Reserved for serialized-state output; the current FE does not emit it and 
BE rejects it.
+  SERIALIZED_STATE = 1,
+}
+
+struct TGroupJoinAggFunction {
+  // Aggregate arguments may reference build, probe, or both sides of a 
matched row pair.
+  1: required Exprs.TExpr aggregate_function

Review Comment:
   [P2] Declare the new GroupJoin descriptor members optional
   
   The new `TGroupJoinAggFunction` fields 1/2 and `TGroupJoinNode` fields 
1/2/20/22/23 are declared `required`. This violates `gensrc/AGENTS.md`'s 
explicit schema-evolution rule that every new field must be optional across 
supported branches. Requiredness makes omission a generated-protocol validation 
failure and prevents compatible omission as these descriptors evolve. Please 
keep the assigned IDs, declare these members optional, and validate mandatory 
execution inputs explicitly in `validate_group_join_node`.



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