Coverage Report

Created: 2026-03-15 17:28

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
0
                                            DataTypePtr return_type) {
64
0
    return FunctionType::create(
65
0
            assert_cast<const DataTypeAggState*>(argument_types[0].get())->get_nested_function(),
66
0
            argument_types, return_type);
67
0
}
Unexecuted instantiation: _ZN5doris22get_agg_state_functionINS_19AggregateStateUnionEEESt10shared_ptrINS_18IAggregateFunctionEERKSt6vectorIS2_IKNS_9IDataTypeEESaIS8_EES8_
Unexecuted instantiation: _ZN5doris22get_agg_state_functionINS_19AggregateStateMergeEEESt10shared_ptrINS_18IAggregateFunctionEERKSt6vectorIS2_IKNS_9IDataTypeEESaIS8_EES8_
68
69
AggFnEvaluator::AggFnEvaluator(const TExprNode& desc, const bool without_key,
70
                               const bool is_window_function)
71
11
        : _fn(desc.fn),
72
11
          _is_merge(desc.agg_expr.is_merge_agg),
73
11
          _without_key(without_key),
74
11
          _is_window_function(is_window_function),
75
11
          _data_type(DataTypeFactory::instance().create_data_type(
76
11
                  desc.fn.ret_type, desc.__isset.is_nullable ? desc.is_nullable : true)) {
77
11
    if (desc.agg_expr.__isset.param_types) {
78
11
        const auto& param_types = desc.agg_expr.param_types;
79
11
        for (const auto& param_type : param_types) {
80
11
            _argument_types_with_sort.push_back(
81
11
                    DataTypeFactory::instance().create_data_type(param_type));
82
11
        }
83
11
    }
84
11
}
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
11
                              AggFnEvaluator** result) {
89
11
    *result =
90
11
            pool->add(AggFnEvaluator::create_unique(desc.nodes[0], without_key, is_window_function)
91
11
                              .release());
92
11
    auto& agg_fn_evaluator = *result;
93
11
    int node_idx = 0;
94
22
    for (int i = 0; i < desc.nodes[0].num_children; ++i) {
95
11
        ++node_idx;
96
11
        VExprSPtr expr;
97
11
        VExprContextSPtr ctx;
98
11
        RETURN_IF_ERROR(VExpr::create_tree_from_thrift(desc.nodes, &node_idx, expr, ctx));
99
11
        agg_fn_evaluator->_input_exprs_ctxs.push_back(ctx);
100
11
    }
101
102
11
    auto sort_size = sort_info.ordering_exprs.size();
103
11
    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
11
    for (int i = 0; i < sort_size; ++i) {
107
0
        agg_fn_evaluator->_sort_description.emplace_back(real_arguments_size + i,
108
0
                                                         sort_info.is_asc_order[i] ? 1 : -1,
109
0
                                                         sort_info.nulls_first[i] ? -1 : 1);
110
0
    }
111
112
    // Pass the real arguments to get functions
113
22
    for (int i = 0; i < real_arguments_size; ++i) {
114
11
        agg_fn_evaluator->_real_argument_types.emplace_back(
115
11
                agg_fn_evaluator->_argument_types_with_sort[i]);
116
11
    }
117
11
    return Status::OK();
118
11
}
119
120
Status AggFnEvaluator::prepare(RuntimeState* state, const RowDescriptor& desc,
121
                               const SlotDescriptor* intermediate_slot_desc,
122
11
                               const SlotDescriptor* output_slot_desc) {
123
11
    DCHECK(intermediate_slot_desc != nullptr);
124
11
    DCHECK(_intermediate_slot_desc == nullptr);
125
11
    _output_slot_desc = output_slot_desc;
126
11
    _intermediate_slot_desc = intermediate_slot_desc;
127
128
11
    Status status = VExpr::prepare(_input_exprs_ctxs, state, desc);
129
11
    RETURN_IF_ERROR(status);
130
131
11
    DataTypes tmp_argument_types;
132
11
    tmp_argument_types.reserve(_input_exprs_ctxs.size());
133
134
11
    std::vector<std::string_view> child_expr_name;
135
136
    // prepare for argument
137
11
    for (auto& _input_exprs_ctx : _input_exprs_ctxs) {
138
11
        auto data_type = _input_exprs_ctx->root()->data_type();
139
11
        tmp_argument_types.emplace_back(data_type);
140
11
        child_expr_name.emplace_back(_input_exprs_ctx->root()->expr_name());
141
11
    }
142
143
11
    std::vector<std::string> column_names;
144
11
    for (const auto& expr_ctx : _input_exprs_ctxs) {
145
11
        const auto& root = expr_ctx->root();
146
11
        if (!root->expr_name().empty() && !root->is_constant()) {
147
11
            column_names.emplace_back(root->expr_name());
148
11
        }
149
11
    }
150
151
11
    const DataTypes& argument_types =
152
11
            _real_argument_types.empty() ? tmp_argument_types : _real_argument_types;
153
154
11
    if (_fn.binary_type == TFunctionBinaryType::JAVA_UDF) {
155
0
        if (config::enable_java_support) {
156
0
            _function = AggregateJavaUdaf::create(_fn, argument_types, _data_type);
157
0
            RETURN_IF_ERROR(static_cast<AggregateJavaUdaf*>(_function.get())->check_udaf(_fn));
158
0
        } 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
11
    } else if (_fn.binary_type == TFunctionBinaryType::PYTHON_UDF) {
164
0
        if (config::enable_python_udf_support) {
165
0
            _function = AggregatePythonUDAF::create(_fn, argument_types, _data_type);
166
0
            RETURN_IF_ERROR(static_cast<AggregatePythonUDAF*>(_function.get())->open());
167
0
            LOG(INFO) << fmt::format(
168
0
                    "Created Python UDAF: {}, runtime_version: {}, function_code: {}",
169
0
                    _fn.name.function_name, _fn.runtime_version, _fn.function_code);
170
0
        } 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
11
    } else if (_fn.binary_type == TFunctionBinaryType::RPC) {
176
0
        _function = AggregateRpcUdaf::create(_fn, argument_types, _data_type);
177
11
    } else if (_fn.binary_type == TFunctionBinaryType::AGG_STATE) {
178
0
        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
0
        if (argument_types[0]->is_nullable()) {
183
0
            return Status::InternalError("Agg state function input type must be not nullable");
184
0
        }
185
0
        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
0
        std::string type_function_name =
192
0
                assert_cast<const DataTypeAggState*>(argument_types[0].get())->get_function_name();
193
0
        if (type_function_name + AGG_UNION_SUFFIX == _fn.name.function_name) {
194
0
            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
0
            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
0
            _function = get_agg_state_function<AggregateStateUnion>(argument_types, _data_type);
205
0
        } else if (type_function_name + AGG_MERGE_SUFFIX == _fn.name.function_name) {
206
0
            auto type = assert_cast<const DataTypeAggState*>(argument_types[0].get())
207
0
                                ->get_nested_function()
208
0
                                ->get_return_type();
209
0
            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
0
            _function = get_agg_state_function<AggregateStateMerge>(argument_types, _data_type);
215
0
        } else {
216
0
            return Status::InternalError("{} not match function {}", argument_types[0]->get_name(),
217
0
                                         _fn.name.function_name);
218
0
        }
219
11
    } else {
220
11
        const bool is_foreach =
221
11
                AggregateFunctionSimpleFactory::is_foreach(_fn.name.function_name) ||
222
11
                AggregateFunctionSimpleFactory::is_foreachv2(_fn.name.function_name);
223
        // Here, only foreachv1 needs special treatment, and v2 can follow the normal code logic.
224
11
        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
11
        } else {
235
11
            _function = AggregateFunctionSimpleFactory::instance().get(
236
11
                    _fn.name.function_name, argument_types, _data_type, _data_type->is_nullable(),
237
11
                    state->be_exec_version(),
238
11
                    {.is_window_function = _is_window_function,
239
11
                     .is_foreach = is_foreach,
240
11
                     .enable_aggregate_function_null_v2 =
241
11
                             state->enable_aggregate_function_null_v2(),
242
11
                     .column_names = std::move(column_names)});
243
11
        }
244
11
    }
245
11
    if (_function == nullptr) {
246
0
        return Status::InternalError("Agg Function {} is not implemented", _fn.signature);
247
0
    }
248
249
11
    if (!_sort_description.empty()) {
250
0
        _function = transform_to_sort_agg_function(_function, _argument_types_with_sort,
251
0
                                                   _sort_description, state);
252
0
    }
253
254
11
    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
11
    if (!AggregateFunctionSimpleFactory::is_foreach(_fn.name.function_name) &&
261
11
        !AggregateFunctionSimpleFactory::is_foreachv2(_fn.name.function_name)) {
262
11
        if (state->be_exec_version() >= BE_VERSION_THAT_SUPPORT_NULLABLE_CHECK) {
263
11
            RETURN_IF_ERROR(
264
11
                    _function->verify_result_type(_without_key, argument_types, _data_type));
265
11
        }
266
11
    }
267
11
    _expr_name = fmt::format("{}({})", _fn.name.function_name, child_expr_name);
268
11
    return Status::OK();
269
11
}
270
271
11
Status AggFnEvaluator::open(RuntimeState* state) {
272
11
    return VExpr::open(_input_exprs_ctxs, state);
273
11
}
274
275
1.04M
void AggFnEvaluator::create(AggregateDataPtr place) {
276
1.04M
    _function->create(place);
277
1.04M
}
278
279
199
void AggFnEvaluator::destroy(AggregateDataPtr place) {
280
199
    _function->destroy(place);
281
199
}
282
283
140
Status AggFnEvaluator::execute_single_add(Block* block, AggregateDataPtr place, Arena& arena) {
284
140
    RETURN_IF_ERROR(_calc_argument_columns(block));
285
140
    _function->add_batch_single_place(block->rows(), place, _agg_columns.data(), arena);
286
140
    return Status::OK();
287
140
}
288
289
Status AggFnEvaluator::execute_batch_add(Block* block, size_t offset, AggregateDataPtr* places,
290
40
                                         Arena& arena, bool agg_many) {
291
40
    RETURN_IF_ERROR(_calc_argument_columns(block));
292
40
    _function->add_batch(block->rows(), places, offset, _agg_columns.data(), arena, agg_many);
293
40
    return Status::OK();
294
40
}
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
24
                                                         const size_t num_rows, Arena& arena) {
305
24
    RETURN_IF_ERROR(_calc_argument_columns(block));
306
24
    _function->streaming_agg_serialize_to_column(_agg_columns.data(), dst, num_rows, arena);
307
24
    return Status::OK();
308
24
}
309
310
146
void AggFnEvaluator::insert_result_info(AggregateDataPtr place, IColumn* column) {
311
146
    _function->insert_result_into(place, *column);
312
146
}
313
314
void AggFnEvaluator::insert_result_info_vec(const std::vector<AggregateDataPtr>& places,
315
11
                                            size_t offset, IColumn* column, const size_t num_rows) {
316
11
    _function->insert_result_into_vec(places, offset, *column, num_rows);
317
11
}
318
319
53
void AggFnEvaluator::reset(AggregateDataPtr place) {
320
53
    _function->reset(place);
321
53
}
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
206
Status AggFnEvaluator::_calc_argument_columns(Block* block) {
344
206
    SCOPED_TIMER(_expr_timer);
345
206
    _agg_columns.resize(_input_exprs_ctxs.size());
346
206
    std::vector<int> column_ids(_input_exprs_ctxs.size());
347
440
    for (int i = 0; i < _input_exprs_ctxs.size(); ++i) {
348
234
        int column_id = -1;
349
234
        RETURN_IF_ERROR(_input_exprs_ctxs[i]->execute(block, &column_id));
350
234
        column_ids[i] = column_id;
351
234
    }
352
206
    materialize_block_inplace(*block, column_ids.data(),
353
206
                              column_ids.data() + _input_exprs_ctxs.size());
354
440
    for (int i = 0; i < _input_exprs_ctxs.size(); ++i) {
355
234
        _agg_columns[i] = block->get_by_position(column_ids[i]).column.get();
356
234
    }
357
206
    return Status::OK();
358
206
}
359
360
52
AggFnEvaluator* AggFnEvaluator::clone(RuntimeState* state, ObjectPool* pool) {
361
52
    return pool->add(AggFnEvaluator::create_unique(*this, state).release());
362
52
}
363
364
AggFnEvaluator::AggFnEvaluator(AggFnEvaluator& evaluator, RuntimeState* state)
365
52
        : _fn(evaluator._fn),
366
52
          _is_merge(evaluator._is_merge),
367
52
          _without_key(evaluator._without_key),
368
52
          _is_window_function(evaluator._is_window_function),
369
52
          _argument_types_with_sort(evaluator._argument_types_with_sort),
370
52
          _real_argument_types(evaluator._real_argument_types),
371
52
          _intermediate_slot_desc(evaluator._intermediate_slot_desc),
372
52
          _output_slot_desc(evaluator._output_slot_desc),
373
52
          _sort_description(evaluator._sort_description),
374
52
          _data_type(evaluator._data_type),
375
52
          _function(evaluator._function),
376
52
          _expr_name(evaluator._expr_name),
377
52
          _agg_columns(evaluator._agg_columns) {
378
52
    if (evaluator._fn.binary_type == TFunctionBinaryType::JAVA_UDF) {
379
0
        DataTypes tmp_argument_types;
380
0
        tmp_argument_types.reserve(evaluator._input_exprs_ctxs.size());
381
        // prepare for argument
382
0
        for (auto& _input_exprs_ctx : evaluator._input_exprs_ctxs) {
383
0
            auto data_type = _input_exprs_ctx->root()->data_type();
384
0
            tmp_argument_types.emplace_back(data_type);
385
0
        }
386
0
        const DataTypes& argument_types =
387
0
                _real_argument_types.empty() ? tmp_argument_types : _real_argument_types;
388
0
        _function = AggregateJavaUdaf::create(evaluator._fn, argument_types, evaluator._data_type);
389
0
        THROW_IF_ERROR(static_cast<AggregateJavaUdaf*>(_function.get())->check_udaf(evaluator._fn));
390
0
    }
391
52
    DCHECK(_function != nullptr);
392
393
52
    _input_exprs_ctxs.resize(evaluator._input_exprs_ctxs.size());
394
103
    for (size_t i = 0; i < _input_exprs_ctxs.size(); i++) {
395
51
        WARN_IF_ERROR(evaluator._input_exprs_ctxs[i]->clone(state, _input_exprs_ctxs[i]), "");
396
51
    }
397
52
}
398
399
Status AggFnEvaluator::check_agg_fn_output(uint32_t key_size,
400
                                           const std::vector<AggFnEvaluator*>& agg_fn,
401
0
                                           const RowDescriptor& output_row_desc) {
402
0
    auto name_and_types = VectorizedUtils::create_name_and_data_types(output_row_desc);
403
0
    for (uint32_t i = key_size, j = 0; i < name_and_types.size(); i++, j++) {
404
0
        auto&& [name, column_type] = name_and_types[i];
405
0
        auto agg_return_type = agg_fn[j]->function()->get_return_type();
406
0
        if (!column_type->equals(*agg_return_type)) {
407
0
            if (!column_type->is_nullable() || agg_return_type->is_nullable() ||
408
0
                !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
0
        }
415
0
    }
416
0
    return Status::OK();
417
0
}
418
419
0
bool AggFnEvaluator::is_blockable() const {
420
0
    return _function->is_blockable() ||
421
0
           std::any_of(_input_exprs_ctxs.begin(), _input_exprs_ctxs.end(),
422
0
                       [](VExprContextSPtr ctx) { return ctx->root()->is_blockable(); });
423
0
}
424
425
#include "common/compile_check_end.h"
426
} // namespace doris