Coverage Report

Created: 2026-03-13 14:44

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
213k
        : _fn(desc.fn),
72
213k
          _is_merge(desc.agg_expr.is_merge_agg),
73
213k
          _without_key(without_key),
74
213k
          _is_window_function(is_window_function),
75
213k
          _data_type(DataTypeFactory::instance().create_data_type(
76
18.4E
                  desc.fn.ret_type, desc.__isset.is_nullable ? desc.is_nullable : true)) {
77
213k
    if (desc.agg_expr.__isset.param_types) {
78
213k
        const auto& param_types = desc.agg_expr.param_types;
79
213k
        for (const auto& param_type : param_types) {
80
172k
            _argument_types_with_sort.push_back(
81
172k
                    DataTypeFactory::instance().create_data_type(param_type));
82
172k
        }
83
213k
    }
84
213k
}
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
213k
                              AggFnEvaluator** result) {
89
213k
    *result =
90
213k
            pool->add(AggFnEvaluator::create_unique(desc.nodes[0], without_key, is_window_function)
91
213k
                              .release());
92
213k
    auto& agg_fn_evaluator = *result;
93
213k
    int node_idx = 0;
94
407k
    for (int i = 0; i < desc.nodes[0].num_children; ++i) {
95
194k
        ++node_idx;
96
194k
        VExprSPtr expr;
97
194k
        VExprContextSPtr ctx;
98
194k
        RETURN_IF_ERROR(VExpr::create_tree_from_thrift(desc.nodes, &node_idx, expr, ctx));
99
194k
        agg_fn_evaluator->_input_exprs_ctxs.push_back(ctx);
100
194k
    }
101
102
213k
    auto sort_size = sort_info.ordering_exprs.size();
103
213k
    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
213k
    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
385k
    for (int i = 0; i < real_arguments_size; ++i) {
114
172k
        agg_fn_evaluator->_real_argument_types.emplace_back(
115
172k
                agg_fn_evaluator->_argument_types_with_sort[i]);
116
172k
    }
117
213k
    return Status::OK();
118
213k
}
119
120
Status AggFnEvaluator::prepare(RuntimeState* state, const RowDescriptor& desc,
121
                               const SlotDescriptor* intermediate_slot_desc,
122
213k
                               const SlotDescriptor* output_slot_desc) {
123
213k
    DCHECK(intermediate_slot_desc != nullptr);
124
213k
    DCHECK(_intermediate_slot_desc == nullptr);
125
213k
    _output_slot_desc = output_slot_desc;
126
213k
    _intermediate_slot_desc = intermediate_slot_desc;
127
128
213k
    Status status = VExpr::prepare(_input_exprs_ctxs, state, desc);
129
213k
    RETURN_IF_ERROR(status);
130
131
213k
    DataTypes tmp_argument_types;
132
213k
    tmp_argument_types.reserve(_input_exprs_ctxs.size());
133
134
213k
    std::vector<std::string_view> child_expr_name;
135
136
    // prepare for argument
137
213k
    for (auto& _input_exprs_ctx : _input_exprs_ctxs) {
138
194k
        auto data_type = _input_exprs_ctx->root()->data_type();
139
194k
        tmp_argument_types.emplace_back(data_type);
140
194k
        child_expr_name.emplace_back(_input_exprs_ctx->root()->expr_name());
141
194k
    }
142
143
213k
    std::vector<std::string> column_names;
144
213k
    for (const auto& expr_ctx : _input_exprs_ctxs) {
145
194k
        const auto& root = expr_ctx->root();
146
194k
        if (!root->expr_name().empty() && !root->is_constant()) {
147
84.6k
            column_names.emplace_back(root->expr_name());
148
84.6k
        }
149
194k
    }
150
151
213k
    const DataTypes& argument_types =
152
213k
            _real_argument_types.empty() ? tmp_argument_types : _real_argument_types;
153
154
213k
    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
213k
    } 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
212k
    } else if (_fn.binary_type == TFunctionBinaryType::RPC) {
176
0
        _function = AggregateRpcUdaf::create(_fn, argument_types, _data_type);
177
212k
    } 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
212k
    } else {
220
212k
        const bool is_foreach =
221
212k
                AggregateFunctionSimpleFactory::is_foreach(_fn.name.function_name) ||
222
212k
                AggregateFunctionSimpleFactory::is_foreachv2(_fn.name.function_name);
223
        // Here, only foreachv1 needs special treatment, and v2 can follow the normal code logic.
224
212k
        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
212k
        } else {
235
212k
            _function = AggregateFunctionSimpleFactory::instance().get(
236
212k
                    _fn.name.function_name, argument_types, _data_type, _data_type->is_nullable(),
237
212k
                    state->be_exec_version(),
238
212k
                    {.is_window_function = _is_window_function,
239
212k
                     .is_foreach = is_foreach,
240
212k
                     .enable_aggregate_function_null_v2 =
241
212k
                             state->enable_aggregate_function_null_v2(),
242
212k
                     .column_names = std::move(column_names)});
243
212k
        }
244
212k
    }
245
213k
    if (_function == nullptr) {
246
0
        return Status::InternalError("Agg Function {} is not implemented", _fn.signature);
247
0
    }
248
249
213k
    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
213k
    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
213k
    if (!AggregateFunctionSimpleFactory::is_foreach(_fn.name.function_name) &&
261
213k
        !AggregateFunctionSimpleFactory::is_foreachv2(_fn.name.function_name)) {
262
213k
        if (state->be_exec_version() >= BE_VERSION_THAT_SUPPORT_NULLABLE_CHECK) {
263
213k
            RETURN_IF_ERROR(
264
213k
                    _function->verify_result_type(_without_key, argument_types, _data_type));
265
213k
        }
266
213k
    }
267
213k
    _expr_name = fmt::format("{}({})", _fn.name.function_name, child_expr_name);
268
213k
    return Status::OK();
269
213k
}
270
271
213k
Status AggFnEvaluator::open(RuntimeState* state) {
272
213k
    return VExpr::open(_input_exprs_ctxs, state);
273
213k
}
274
275
6.22M
void AggFnEvaluator::create(AggregateDataPtr place) {
276
6.22M
    _function->create(place);
277
6.22M
}
278
279
9.14k
void AggFnEvaluator::destroy(AggregateDataPtr place) {
280
9.14k
    _function->destroy(place);
281
9.14k
}
282
283
303k
Status AggFnEvaluator::execute_single_add(Block* block, AggregateDataPtr place, Arena& arena) {
284
303k
    RETURN_IF_ERROR(_calc_argument_columns(block));
285
303k
    _function->add_batch_single_place(block->rows(), place, _agg_columns.data(), arena);
286
303k
    return Status::OK();
287
303k
}
288
289
Status AggFnEvaluator::execute_batch_add(Block* block, size_t offset, AggregateDataPtr* places,
290
95.4k
                                         Arena& arena, bool agg_many) {
291
95.4k
    RETURN_IF_ERROR(_calc_argument_columns(block));
292
95.4k
    _function->add_batch(block->rows(), places, offset, _agg_columns.data(), arena, agg_many);
293
95.4k
    return Status::OK();
294
95.4k
}
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
26
                                                         const size_t num_rows, Arena& arena) {
305
26
    RETURN_IF_ERROR(_calc_argument_columns(block));
306
26
    _function->streaming_agg_serialize_to_column(_agg_columns.data(), dst, num_rows, arena);
307
26
    return Status::OK();
308
26
}
309
310
99.9k
void AggFnEvaluator::insert_result_info(AggregateDataPtr place, IColumn* column) {
311
99.9k
    _function->insert_result_into(place, *column);
312
99.9k
}
313
314
void AggFnEvaluator::insert_result_info_vec(const std::vector<AggregateDataPtr>& places,
315
92.7k
                                            size_t offset, IColumn* column, const size_t num_rows) {
316
92.7k
    _function->insert_result_into_vec(places, offset, *column, num_rows);
317
92.7k
}
318
319
16.4k
void AggFnEvaluator::reset(AggregateDataPtr place) {
320
16.4k
    _function->reset(place);
321
16.4k
}
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
399k
Status AggFnEvaluator::_calc_argument_columns(Block* block) {
344
399k
    SCOPED_TIMER(_expr_timer);
345
399k
    _agg_columns.resize(_input_exprs_ctxs.size());
346
399k
    std::vector<int> column_ids(_input_exprs_ctxs.size());
347
714k
    for (int i = 0; i < _input_exprs_ctxs.size(); ++i) {
348
315k
        int column_id = -1;
349
315k
        RETURN_IF_ERROR(_input_exprs_ctxs[i]->execute(block, &column_id));
350
314k
        column_ids[i] = column_id;
351
314k
    }
352
399k
    materialize_block_inplace(*block, column_ids.data(),
353
399k
                              column_ids.data() + _input_exprs_ctxs.size());
354
714k
    for (int i = 0; i < _input_exprs_ctxs.size(); ++i) {
355
315k
        _agg_columns[i] = block->get_by_position(column_ids[i]).column.get();
356
315k
    }
357
399k
    return Status::OK();
358
399k
}
359
360
396k
AggFnEvaluator* AggFnEvaluator::clone(RuntimeState* state, ObjectPool* pool) {
361
396k
    return pool->add(AggFnEvaluator::create_unique(*this, state).release());
362
396k
}
363
364
AggFnEvaluator::AggFnEvaluator(AggFnEvaluator& evaluator, RuntimeState* state)
365
395k
        : _fn(evaluator._fn),
366
395k
          _is_merge(evaluator._is_merge),
367
395k
          _without_key(evaluator._without_key),
368
395k
          _is_window_function(evaluator._is_window_function),
369
395k
          _argument_types_with_sort(evaluator._argument_types_with_sort),
370
395k
          _real_argument_types(evaluator._real_argument_types),
371
395k
          _intermediate_slot_desc(evaluator._intermediate_slot_desc),
372
395k
          _output_slot_desc(evaluator._output_slot_desc),
373
395k
          _sort_description(evaluator._sort_description),
374
395k
          _data_type(evaluator._data_type),
375
395k
          _function(evaluator._function),
376
395k
          _expr_name(evaluator._expr_name),
377
395k
          _agg_columns(evaluator._agg_columns) {
378
395k
    if (evaluator._fn.binary_type == TFunctionBinaryType::JAVA_UDF) {
379
603
        DataTypes tmp_argument_types;
380
603
        tmp_argument_types.reserve(evaluator._input_exprs_ctxs.size());
381
        // prepare for argument
382
668
        for (auto& _input_exprs_ctx : evaluator._input_exprs_ctxs) {
383
668
            auto data_type = _input_exprs_ctx->root()->data_type();
384
668
            tmp_argument_types.emplace_back(data_type);
385
668
        }
386
603
        const DataTypes& argument_types =
387
603
                _real_argument_types.empty() ? tmp_argument_types : _real_argument_types;
388
603
        _function = AggregateJavaUdaf::create(evaluator._fn, argument_types, evaluator._data_type);
389
603
        THROW_IF_ERROR(static_cast<AggregateJavaUdaf*>(_function.get())->check_udaf(evaluator._fn));
390
603
    }
391
395k
    DCHECK(_function != nullptr);
392
393
395k
    _input_exprs_ctxs.resize(evaluator._input_exprs_ctxs.size());
394
746k
    for (size_t i = 0; i < _input_exprs_ctxs.size(); i++) {
395
351k
        WARN_IF_ERROR(evaluator._input_exprs_ctxs[i]->clone(state, _input_exprs_ctxs[i]), "");
396
351k
    }
397
395k
}
398
399
Status AggFnEvaluator::check_agg_fn_output(uint32_t key_size,
400
                                           const std::vector<AggFnEvaluator*>& agg_fn,
401
36.5k
                                           const RowDescriptor& output_row_desc) {
402
36.5k
    auto name_and_types = VectorizedUtils::create_name_and_data_types(output_row_desc);
403
145k
    for (uint32_t i = key_size, j = 0; i < name_and_types.size(); i++, j++) {
404
109k
        auto&& [name, column_type] = name_and_types[i];
405
109k
        auto agg_return_type = agg_fn[j]->function()->get_return_type();
406
109k
        if (!column_type->equals(*agg_return_type)) {
407
16.7k
            if (!column_type->is_nullable() || agg_return_type->is_nullable() ||
408
16.7k
                !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
16.7k
        }
415
109k
    }
416
36.5k
    return Status::OK();
417
36.5k
}
418
419
1.57M
bool AggFnEvaluator::is_blockable() const {
420
1.57M
    return _function->is_blockable() ||
421
1.57M
           std::any_of(_input_exprs_ctxs.begin(), _input_exprs_ctxs.end(),
422
1.57M
                       [](VExprContextSPtr ctx) { return ctx->root()->is_blockable(); });
423
1.57M
}
424
425
#include "common/compile_check_end.h"
426
} // namespace doris