Coverage Report

Created: 2026-03-16 13:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/vectorized_agg_fn.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exprs/vectorized_agg_fn.h"
19
20
#include <fmt/format.h>
21
#include <fmt/ranges.h> // IWYU pragma: keep
22
#include <gen_cpp/Exprs_types.h>
23
#include <gen_cpp/PlanNodes_types.h>
24
#include <glog/logging.h>
25
26
#include <memory>
27
#include <ostream>
28
#include <string_view>
29
30
#include "common/config.h"
31
#include "common/object_pool.h"
32
#include "core/block/block.h"
33
#include "core/block/column_with_type_and_name.h"
34
#include "core/block/materialize_block.h"
35
#include "core/data_type/data_type_agg_state.h"
36
#include "core/data_type/data_type_factory.hpp"
37
#include "exec/common/util.hpp"
38
#include "exprs/aggregate/aggregate_function_ai_agg.h"
39
#include "exprs/aggregate/aggregate_function_java_udaf.h"
40
#include "exprs/aggregate/aggregate_function_python_udaf.h"
41
#include "exprs/aggregate/aggregate_function_rpc.h"
42
#include "exprs/aggregate/aggregate_function_simple_factory.h"
43
#include "exprs/aggregate/aggregate_function_sort.h"
44
#include "exprs/aggregate/aggregate_function_state_merge.h"
45
#include "exprs/aggregate/aggregate_function_state_union.h"
46
#include "exprs/vexpr.h"
47
#include "exprs/vexpr_context.h"
48
49
static constexpr int64_t BE_VERSION_THAT_SUPPORT_NULLABLE_CHECK = 8;
50
51
namespace doris {
52
class RowDescriptor;
53
class Arena;
54
class BufferWritable;
55
class IColumn;
56
} // namespace doris
57
58
namespace doris {
59
#include "common/compile_check_begin.h"
60
61
template <class FunctionType>
62
AggregateFunctionPtr get_agg_state_function(const DataTypes& argument_types,
63
499
                                            DataTypePtr return_type) {
64
499
    return FunctionType::create(
65
499
            assert_cast<const DataTypeAggState*>(argument_types[0].get())->get_nested_function(),
66
499
            argument_types, return_type);
67
499
}
_ZN5doris22get_agg_state_functionINS_19AggregateStateUnionEEESt10shared_ptrINS_18IAggregateFunctionEERKSt6vectorIS2_IKNS_9IDataTypeEESaIS8_EES8_
Line
Count
Source
63
159
                                            DataTypePtr return_type) {
64
159
    return FunctionType::create(
65
159
            assert_cast<const DataTypeAggState*>(argument_types[0].get())->get_nested_function(),
66
159
            argument_types, return_type);
67
159
}
_ZN5doris22get_agg_state_functionINS_19AggregateStateMergeEEESt10shared_ptrINS_18IAggregateFunctionEERKSt6vectorIS2_IKNS_9IDataTypeEESaIS8_EES8_
Line
Count
Source
63
340
                                            DataTypePtr return_type) {
64
340
    return FunctionType::create(
65
340
            assert_cast<const DataTypeAggState*>(argument_types[0].get())->get_nested_function(),
66
340
            argument_types, return_type);
67
340
}
68
69
AggFnEvaluator::AggFnEvaluator(const TExprNode& desc, const bool without_key,
70
                               const bool is_window_function)
71
221k
        : _fn(desc.fn),
72
221k
          _is_merge(desc.agg_expr.is_merge_agg),
73
221k
          _without_key(without_key),
74
221k
          _is_window_function(is_window_function),
75
221k
          _data_type(DataTypeFactory::instance().create_data_type(
76
18.4E
                  desc.fn.ret_type, desc.__isset.is_nullable ? desc.is_nullable : true)) {
77
221k
    if (desc.agg_expr.__isset.param_types) {
78
221k
        const auto& param_types = desc.agg_expr.param_types;
79
221k
        for (const auto& param_type : param_types) {
80
177k
            _argument_types_with_sort.push_back(
81
177k
                    DataTypeFactory::instance().create_data_type(param_type));
82
177k
        }
83
221k
    }
84
221k
}
85
86
Status AggFnEvaluator::create(ObjectPool* pool, const TExpr& desc, const TSortInfo& sort_info,
87
                              const bool without_key, const bool is_window_function,
88
221k
                              AggFnEvaluator** result) {
89
221k
    *result =
90
221k
            pool->add(AggFnEvaluator::create_unique(desc.nodes[0], without_key, is_window_function)
91
221k
                              .release());
92
221k
    auto& agg_fn_evaluator = *result;
93
221k
    int node_idx = 0;
94
422k
    for (int i = 0; i < desc.nodes[0].num_children; ++i) {
95
201k
        ++node_idx;
96
201k
        VExprSPtr expr;
97
201k
        VExprContextSPtr ctx;
98
201k
        RETURN_IF_ERROR(VExpr::create_tree_from_thrift(desc.nodes, &node_idx, expr, ctx));
99
201k
        agg_fn_evaluator->_input_exprs_ctxs.push_back(ctx);
100
201k
    }
101
102
221k
    auto sort_size = sort_info.ordering_exprs.size();
103
221k
    auto real_arguments_size = agg_fn_evaluator->_argument_types_with_sort.size() - sort_size;
104
    // Child arguments contains [real arguments, order by arguments], we pass the arguments
105
    // to the order by functions
106
221k
    for (int i = 0; i < sort_size; ++i) {
107
159
        agg_fn_evaluator->_sort_description.emplace_back(real_arguments_size + i,
108
159
                                                         sort_info.is_asc_order[i] ? 1 : -1,
109
159
                                                         sort_info.nulls_first[i] ? -1 : 1);
110
159
    }
111
112
    // Pass the real arguments to get functions
113
398k
    for (int i = 0; i < real_arguments_size; ++i) {
114
177k
        agg_fn_evaluator->_real_argument_types.emplace_back(
115
177k
                agg_fn_evaluator->_argument_types_with_sort[i]);
116
177k
    }
117
221k
    return Status::OK();
118
221k
}
119
120
Status AggFnEvaluator::prepare(RuntimeState* state, const RowDescriptor& desc,
121
                               const SlotDescriptor* intermediate_slot_desc,
122
221k
                               const SlotDescriptor* output_slot_desc) {
123
221k
    DCHECK(intermediate_slot_desc != nullptr);
124
221k
    DCHECK(_intermediate_slot_desc == nullptr);
125
221k
    _output_slot_desc = output_slot_desc;
126
221k
    _intermediate_slot_desc = intermediate_slot_desc;
127
128
221k
    Status status = VExpr::prepare(_input_exprs_ctxs, state, desc);
129
221k
    RETURN_IF_ERROR(status);
130
131
221k
    DataTypes tmp_argument_types;
132
221k
    tmp_argument_types.reserve(_input_exprs_ctxs.size());
133
134
221k
    std::vector<std::string_view> child_expr_name;
135
136
    // prepare for argument
137
221k
    for (auto& _input_exprs_ctx : _input_exprs_ctxs) {
138
201k
        auto data_type = _input_exprs_ctx->root()->data_type();
139
201k
        tmp_argument_types.emplace_back(data_type);
140
201k
        child_expr_name.emplace_back(_input_exprs_ctx->root()->expr_name());
141
201k
    }
142
143
221k
    std::vector<std::string> column_names;
144
221k
    for (const auto& expr_ctx : _input_exprs_ctxs) {
145
201k
        const auto& root = expr_ctx->root();
146
201k
        if (!root->expr_name().empty() && !root->is_constant()) {
147
87.0k
            column_names.emplace_back(root->expr_name());
148
87.0k
        }
149
201k
    }
150
151
221k
    const DataTypes& argument_types =
152
221k
            _real_argument_types.empty() ? tmp_argument_types : _real_argument_types;
153
154
221k
    if (_fn.binary_type == TFunctionBinaryType::JAVA_UDF) {
155
115
        if (config::enable_java_support) {
156
115
            _function = AggregateJavaUdaf::create(_fn, argument_types, _data_type);
157
115
            RETURN_IF_ERROR(static_cast<AggregateJavaUdaf*>(_function.get())->check_udaf(_fn));
158
115
        } else {
159
0
            return Status::InternalError(
160
0
                    "Java UDAF is not enabled, you can change be config enable_java_support to "
161
0
                    "true and restart be.");
162
0
        }
163
221k
    } else if (_fn.binary_type == TFunctionBinaryType::PYTHON_UDF) {
164
633
        if (config::enable_python_udf_support) {
165
633
            _function = AggregatePythonUDAF::create(_fn, argument_types, _data_type);
166
633
            RETURN_IF_ERROR(static_cast<AggregatePythonUDAF*>(_function.get())->open());
167
633
            LOG(INFO) << fmt::format(
168
633
                    "Created Python UDAF: {}, runtime_version: {}, function_code: {}",
169
633
                    _fn.name.function_name, _fn.runtime_version, _fn.function_code);
170
633
        } else {
171
0
            return Status::InternalError(
172
0
                    "Python UDAF is not enabled, you can change be config "
173
0
                    "enable_python_udf_support to true and restart be.");
174
0
        }
175
220k
    } else if (_fn.binary_type == TFunctionBinaryType::RPC) {
176
0
        _function = AggregateRpcUdaf::create(_fn, argument_types, _data_type);
177
220k
    } else if (_fn.binary_type == TFunctionBinaryType::AGG_STATE) {
178
500
        if (argument_types.size() != 1) {
179
0
            return Status::InternalError("Agg state Function must input 1 argument but get {}",
180
0
                                         argument_types.size());
181
0
        }
182
500
        if (argument_types[0]->is_nullable()) {
183
0
            return Status::InternalError("Agg state function input type must be not nullable");
184
0
        }
185
500
        if (argument_types[0]->get_primitive_type() != PrimitiveType::TYPE_AGG_STATE) {
186
0
            return Status::InternalError(
187
0
                    "Agg state function input type must be agg_state but get {}",
188
0
                    argument_types[0]->get_family_name());
189
0
        }
190
191
500
        std::string type_function_name =
192
500
                assert_cast<const DataTypeAggState*>(argument_types[0].get())->get_function_name();
193
500
        if (type_function_name + AGG_UNION_SUFFIX == _fn.name.function_name) {
194
159
            if (_data_type->is_nullable()) {
195
0
                return Status::InternalError(
196
0
                        "Union function return type must be not nullable, real={}",
197
0
                        _data_type->get_name());
198
0
            }
199
159
            if (_data_type->get_primitive_type() != PrimitiveType::TYPE_AGG_STATE) {
200
0
                return Status::InternalError(
201
0
                        "Union function return type must be AGG_STATE, real={}",
202
0
                        _data_type->get_name());
203
0
            }
204
159
            _function = get_agg_state_function<AggregateStateUnion>(argument_types, _data_type);
205
341
        } else if (type_function_name + AGG_MERGE_SUFFIX == _fn.name.function_name) {
206
340
            auto type = assert_cast<const DataTypeAggState*>(argument_types[0].get())
207
340
                                ->get_nested_function()
208
340
                                ->get_return_type();
209
340
            if (!type->equals(*_data_type)) {
210
0
                return Status::InternalError("{}'s expect return type is {}, but input {}",
211
0
                                             argument_types[0]->get_name(), type->get_name(),
212
0
                                             _data_type->get_name());
213
0
            }
214
340
            _function = get_agg_state_function<AggregateStateMerge>(argument_types, _data_type);
215
340
        } else {
216
1
            return Status::InternalError("{} not match function {}", argument_types[0]->get_name(),
217
1
                                         _fn.name.function_name);
218
1
        }
219
220k
    } else {
220
220k
        const bool is_foreach =
221
220k
                AggregateFunctionSimpleFactory::is_foreach(_fn.name.function_name) ||
222
220k
                AggregateFunctionSimpleFactory::is_foreachv2(_fn.name.function_name);
223
        // Here, only foreachv1 needs special treatment, and v2 can follow the normal code logic.
224
220k
        if (AggregateFunctionSimpleFactory::is_foreach(_fn.name.function_name)) {
225
0
            _function = AggregateFunctionSimpleFactory::instance().get(
226
0
                    _fn.name.function_name, argument_types, _data_type,
227
0
                    AggregateFunctionSimpleFactory::result_nullable_by_foreach(_data_type),
228
0
                    state->be_exec_version(),
229
0
                    {.is_window_function = _is_window_function,
230
0
                     .is_foreach = is_foreach,
231
0
                     .enable_aggregate_function_null_v2 =
232
0
                             state->enable_aggregate_function_null_v2(),
233
0
                     .column_names = std::move(column_names)});
234
220k
        } else {
235
220k
            _function = AggregateFunctionSimpleFactory::instance().get(
236
220k
                    _fn.name.function_name, argument_types, _data_type, _data_type->is_nullable(),
237
220k
                    state->be_exec_version(),
238
220k
                    {.is_window_function = _is_window_function,
239
220k
                     .is_foreach = is_foreach,
240
220k
                     .enable_aggregate_function_null_v2 =
241
220k
                             state->enable_aggregate_function_null_v2(),
242
220k
                     .column_names = std::move(column_names)});
243
220k
        }
244
220k
    }
245
221k
    if (_function == nullptr) {
246
0
        return Status::InternalError("Agg Function {} is not implemented", _fn.signature);
247
0
    }
248
249
221k
    if (!_sort_description.empty()) {
250
129
        _function = transform_to_sort_agg_function(_function, _argument_types_with_sort,
251
129
                                                   _sort_description, state);
252
129
    }
253
254
221k
    if (_fn.name.function_name == "ai_agg") {
255
0
        _function->set_query_context(state->get_query_ctx());
256
0
    }
257
258
    // Foreachv2, like foreachv1, does not check the return type,
259
    // because its return type is related to the internal agg.
260
221k
    if (!AggregateFunctionSimpleFactory::is_foreach(_fn.name.function_name) &&
261
221k
        !AggregateFunctionSimpleFactory::is_foreachv2(_fn.name.function_name)) {
262
221k
        if (state->be_exec_version() >= BE_VERSION_THAT_SUPPORT_NULLABLE_CHECK) {
263
221k
            RETURN_IF_ERROR(
264
221k
                    _function->verify_result_type(_without_key, argument_types, _data_type));
265
221k
        }
266
221k
    }
267
221k
    _expr_name = fmt::format("{}({})", _fn.name.function_name, child_expr_name);
268
221k
    return Status::OK();
269
221k
}
270
271
221k
Status AggFnEvaluator::open(RuntimeState* state) {
272
221k
    return VExpr::open(_input_exprs_ctxs, state);
273
221k
}
274
275
3.81M
void AggFnEvaluator::create(AggregateDataPtr place) {
276
3.81M
    _function->create(place);
277
3.81M
}
278
279
7.45k
void AggFnEvaluator::destroy(AggregateDataPtr place) {
280
7.45k
    _function->destroy(place);
281
7.45k
}
282
283
327k
Status AggFnEvaluator::execute_single_add(Block* block, AggregateDataPtr place, Arena& arena) {
284
327k
    RETURN_IF_ERROR(_calc_argument_columns(block));
285
327k
    _function->add_batch_single_place(block->rows(), place, _agg_columns.data(), arena);
286
327k
    return Status::OK();
287
327k
}
288
289
Status AggFnEvaluator::execute_batch_add(Block* block, size_t offset, AggregateDataPtr* places,
290
90.9k
                                         Arena& arena, bool agg_many) {
291
90.9k
    RETURN_IF_ERROR(_calc_argument_columns(block));
292
90.9k
    _function->add_batch(block->rows(), places, offset, _agg_columns.data(), arena, agg_many);
293
90.9k
    return Status::OK();
294
90.9k
}
295
296
Status AggFnEvaluator::execute_batch_add_selected(Block* block, size_t offset,
297
2
                                                  AggregateDataPtr* places, Arena& arena) {
298
2
    RETURN_IF_ERROR(_calc_argument_columns(block));
299
2
    _function->add_batch_selected(block->rows(), places, offset, _agg_columns.data(), arena);
300
2
    return Status::OK();
301
2
}
302
303
Status AggFnEvaluator::streaming_agg_serialize_to_column(Block* block, MutableColumnPtr& dst,
304
44
                                                         const size_t num_rows, Arena& arena) {
305
44
    RETURN_IF_ERROR(_calc_argument_columns(block));
306
44
    _function->streaming_agg_serialize_to_column(_agg_columns.data(), dst, num_rows, arena);
307
44
    return Status::OK();
308
44
}
309
310
103k
void AggFnEvaluator::insert_result_info(AggregateDataPtr place, IColumn* column) {
311
103k
    _function->insert_result_into(place, *column);
312
103k
}
313
314
void AggFnEvaluator::insert_result_info_vec(const std::vector<AggregateDataPtr>& places,
315
92.0k
                                            size_t offset, IColumn* column, const size_t num_rows) {
316
92.0k
    _function->insert_result_into_vec(places, offset, *column, num_rows);
317
92.0k
}
318
319
16.3k
void AggFnEvaluator::reset(AggregateDataPtr place) {
320
16.3k
    _function->reset(place);
321
16.3k
}
322
323
0
std::string AggFnEvaluator::debug_string(const std::vector<AggFnEvaluator*>& exprs) {
324
0
    std::stringstream out;
325
0
    out << "[";
326
327
0
    for (int i = 0; i < exprs.size(); ++i) {
328
0
        out << (i == 0 ? "" : " ") << exprs[i]->debug_string();
329
0
    }
330
331
0
    out << "]";
332
0
    return out.str();
333
0
}
334
335
0
std::string AggFnEvaluator::debug_string() const {
336
0
    std::stringstream out;
337
0
    out << "AggFnEvaluator(";
338
0
    out << _fn.signature;
339
0
    out << ")";
340
0
    return out.str();
341
0
}
342
343
418k
Status AggFnEvaluator::_calc_argument_columns(Block* block) {
344
418k
    SCOPED_TIMER(_expr_timer);
345
418k
    _agg_columns.resize(_input_exprs_ctxs.size());
346
418k
    std::vector<int> column_ids(_input_exprs_ctxs.size());
347
740k
    for (int i = 0; i < _input_exprs_ctxs.size(); ++i) {
348
322k
        int column_id = -1;
349
322k
        RETURN_IF_ERROR(_input_exprs_ctxs[i]->execute(block, &column_id));
350
322k
        column_ids[i] = column_id;
351
322k
    }
352
418k
    materialize_block_inplace(*block, column_ids.data(),
353
418k
                              column_ids.data() + _input_exprs_ctxs.size());
354
741k
    for (int i = 0; i < _input_exprs_ctxs.size(); ++i) {
355
322k
        _agg_columns[i] = block->get_by_position(column_ids[i]).column.get();
356
322k
    }
357
418k
    return Status::OK();
358
418k
}
359
360
412k
AggFnEvaluator* AggFnEvaluator::clone(RuntimeState* state, ObjectPool* pool) {
361
412k
    return pool->add(AggFnEvaluator::create_unique(*this, state).release());
362
412k
}
363
364
AggFnEvaluator::AggFnEvaluator(AggFnEvaluator& evaluator, RuntimeState* state)
365
412k
        : _fn(evaluator._fn),
366
412k
          _is_merge(evaluator._is_merge),
367
412k
          _without_key(evaluator._without_key),
368
412k
          _is_window_function(evaluator._is_window_function),
369
412k
          _argument_types_with_sort(evaluator._argument_types_with_sort),
370
412k
          _real_argument_types(evaluator._real_argument_types),
371
412k
          _intermediate_slot_desc(evaluator._intermediate_slot_desc),
372
412k
          _output_slot_desc(evaluator._output_slot_desc),
373
412k
          _sort_description(evaluator._sort_description),
374
412k
          _data_type(evaluator._data_type),
375
412k
          _function(evaluator._function),
376
412k
          _expr_name(evaluator._expr_name),
377
412k
          _agg_columns(evaluator._agg_columns) {
378
412k
    if (evaluator._fn.binary_type == TFunctionBinaryType::JAVA_UDF) {
379
607
        DataTypes tmp_argument_types;
380
607
        tmp_argument_types.reserve(evaluator._input_exprs_ctxs.size());
381
        // prepare for argument
382
671
        for (auto& _input_exprs_ctx : evaluator._input_exprs_ctxs) {
383
671
            auto data_type = _input_exprs_ctx->root()->data_type();
384
671
            tmp_argument_types.emplace_back(data_type);
385
671
        }
386
607
        const DataTypes& argument_types =
387
607
                _real_argument_types.empty() ? tmp_argument_types : _real_argument_types;
388
607
        _function = AggregateJavaUdaf::create(evaluator._fn, argument_types, evaluator._data_type);
389
607
        THROW_IF_ERROR(static_cast<AggregateJavaUdaf*>(_function.get())->check_udaf(evaluator._fn));
390
607
    }
391
412k
    DCHECK(_function != nullptr);
392
393
412k
    _input_exprs_ctxs.resize(evaluator._input_exprs_ctxs.size());
394
771k
    for (size_t i = 0; i < _input_exprs_ctxs.size(); i++) {
395
358k
        WARN_IF_ERROR(evaluator._input_exprs_ctxs[i]->clone(state, _input_exprs_ctxs[i]), "");
396
358k
    }
397
412k
}
398
399
Status AggFnEvaluator::check_agg_fn_output(uint32_t key_size,
400
                                           const std::vector<AggFnEvaluator*>& agg_fn,
401
39.4k
                                           const RowDescriptor& output_row_desc) {
402
39.4k
    auto name_and_types = VectorizedUtils::create_name_and_data_types(output_row_desc);
403
153k
    for (uint32_t i = key_size, j = 0; i < name_and_types.size(); i++, j++) {
404
113k
        auto&& [name, column_type] = name_and_types[i];
405
113k
        auto agg_return_type = agg_fn[j]->function()->get_return_type();
406
113k
        if (!column_type->equals(*agg_return_type)) {
407
17.5k
            if (!column_type->is_nullable() || agg_return_type->is_nullable() ||
408
17.5k
                !remove_nullable(column_type)->equals(*agg_return_type)) {
409
0
                return Status::InternalError(
410
0
                        "column_type not match data_types in agg node, column_type={}, "
411
0
                        "data_types={},column name={}",
412
0
                        column_type->get_name(), agg_return_type->get_name(), name);
413
0
            }
414
17.5k
        }
415
113k
    }
416
39.4k
    return Status::OK();
417
39.4k
}
418
419
1.61M
bool AggFnEvaluator::is_blockable() const {
420
1.61M
    return _function->is_blockable() ||
421
1.61M
           std::any_of(_input_exprs_ctxs.begin(), _input_exprs_ctxs.end(),
422
1.60M
                       [](VExprContextSPtr ctx) { return ctx->root()->is_blockable(); });
423
1.61M
}
424
425
#include "common/compile_check_end.h"
426
} // namespace doris