Coverage Report

Created: 2026-07-27 18:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/vectorized_fn_call.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_fn_call.h"
19
20
#include <fmt/compile.h>
21
#include <fmt/format.h>
22
#include <fmt/ranges.h> // IWYU pragma: keep
23
#include <gen_cpp/Opcodes_types.h>
24
#include <gen_cpp/Types_types.h>
25
26
#include <memory>
27
#include <optional>
28
#include <ostream>
29
#include <set>
30
31
#include "common/config.h"
32
#include "common/exception.h"
33
#include "common/logging.h"
34
#include "common/status.h"
35
#include "common/utils.h"
36
#include "core/assert_cast.h"
37
#include "core/block/block.h"
38
#include "core/block/column_numbers.h"
39
#include "core/column/column.h"
40
#include "core/column/column_array.h"
41
#include "core/column/column_nullable.h"
42
#include "core/column/column_vector.h"
43
#include "core/data_type/data_type.h"
44
#include "core/data_type/data_type_agg_state.h"
45
#include "core/types.h"
46
#include "exec/common/util.hpp"
47
#include "exec/pipeline/pipeline_task.h"
48
#include "exprs/function/array/function_array_distance.h"
49
#include "exprs/function/function_agg_state.h"
50
#include "exprs/function/function_fake.h"
51
#include "exprs/function/function_java_udf.h"
52
#include "exprs/function/function_python_udf.h"
53
#include "exprs/function/function_rpc.h"
54
#include "exprs/function/simple_function_factory.h"
55
#include "exprs/function_context.h"
56
#include "exprs/varray_literal.h"
57
#include "exprs/vcast_expr.h"
58
#include "exprs/vexpr_context.h"
59
#include "exprs/virtual_slot_ref.h"
60
#include "exprs/vliteral.h"
61
#include "runtime/runtime_state.h"
62
#include "storage/index/ann/ann_index.h"
63
#include "storage/index/ann/ann_index_iterator.h"
64
#include "storage/index/ann/ann_search_params.h"
65
#include "storage/index/index_reader.h"
66
#include "storage/index/zone_map/zonemap_eval_context.h"
67
#include "storage/segment/column_reader.h"
68
#include "storage/segment/virtual_column_iterator.h"
69
#include "util/simd/parquet_kernels.h"
70
71
namespace doris {
72
class RowDescriptor;
73
class RuntimeState;
74
class TExprNode;
75
} // namespace doris
76
77
namespace doris {
78
79
const std::string AGG_STATE_SUFFIX = "_state";
80
81
// Now left child is a function call, we need to check if it is a distance function
82
const static std::set<std::string> DISTANCE_FUNCS = {L2DistanceApproximate::name,
83
                                                     InnerProductApproximate::name};
84
const static std::set<TExprOpcode::type> OPS_FOR_ANN_RANGE_SEARCH = {
85
        TExprOpcode::GE, TExprOpcode::LE, TExprOpcode::LE, TExprOpcode::GT, TExprOpcode::LT};
86
87
namespace {
88
89
using simd::RawComparisonOp;
90
91
12.9k
std::optional<RawComparisonOp> raw_comparison_op(std::string_view function_name, bool reverse) {
92
12.9k
    RawComparisonOp op;
93
12.9k
    if (function_name == "eq") {
94
3.20k
        op = RawComparisonOp::EQ;
95
9.79k
    } else if (function_name == "ne") {
96
220
        op = RawComparisonOp::NE;
97
9.57k
    } else if (function_name == "lt") {
98
714
        op = RawComparisonOp::LT;
99
8.86k
    } else if (function_name == "le") {
100
444
        op = RawComparisonOp::LE;
101
8.42k
    } else if (function_name == "gt") {
102
2.61k
        op = RawComparisonOp::GT;
103
5.80k
    } else if (function_name == "ge") {
104
4.22k
        op = RawComparisonOp::GE;
105
4.22k
    } else {
106
1.57k
        return std::nullopt;
107
1.57k
    }
108
11.4k
    if (!reverse || op == RawComparisonOp::EQ || op == RawComparisonOp::NE) {
109
11.4k
        return op;
110
11.4k
    }
111
1
    switch (op) {
112
1
    case RawComparisonOp::LT:
113
1
        return RawComparisonOp::GT;
114
0
    case RawComparisonOp::LE:
115
0
        return RawComparisonOp::GE;
116
0
    case RawComparisonOp::GT:
117
0
        return RawComparisonOp::LT;
118
0
    case RawComparisonOp::GE:
119
0
        return RawComparisonOp::LE;
120
0
    case RawComparisonOp::EQ:
121
0
    case RawComparisonOp::NE:
122
0
        break;
123
1
    }
124
0
    __builtin_unreachable();
125
1
}
126
127
template <typename T, PrimitiveType PT>
128
void execute_raw_comparison(const uint8_t* values, size_t num_values, const Field& literal,
129
2.09k
                            RawComparisonOp op, uint8_t* matches) {
130
2.09k
    const T rhs = literal.get<PT>();
131
2.09k
    simd::raw_compare(values, num_values, rhs, op, matches);
132
2.09k
}
vectorized_fn_call.cpp:_ZN5doris12_GLOBAL__N_122execute_raw_comparisonIiLNS_13PrimitiveTypeE5EEEvPKhmRKNS_5FieldENS_4simd15RawComparisonOpEPh
Line
Count
Source
129
1.87k
                            RawComparisonOp op, uint8_t* matches) {
130
1.87k
    const T rhs = literal.get<PT>();
131
1.87k
    simd::raw_compare(values, num_values, rhs, op, matches);
132
1.87k
}
vectorized_fn_call.cpp:_ZN5doris12_GLOBAL__N_122execute_raw_comparisonIlLNS_13PrimitiveTypeE6EEEvPKhmRKNS_5FieldENS_4simd15RawComparisonOpEPh
Line
Count
Source
129
123
                            RawComparisonOp op, uint8_t* matches) {
130
123
    const T rhs = literal.get<PT>();
131
123
    simd::raw_compare(values, num_values, rhs, op, matches);
132
123
}
vectorized_fn_call.cpp:_ZN5doris12_GLOBAL__N_122execute_raw_comparisonIfLNS_13PrimitiveTypeE8EEEvPKhmRKNS_5FieldENS_4simd15RawComparisonOpEPh
Line
Count
Source
129
8
                            RawComparisonOp op, uint8_t* matches) {
130
8
    const T rhs = literal.get<PT>();
131
8
    simd::raw_compare(values, num_values, rhs, op, matches);
132
8
}
vectorized_fn_call.cpp:_ZN5doris12_GLOBAL__N_122execute_raw_comparisonIdLNS_13PrimitiveTypeE9EEEvPKhmRKNS_5FieldENS_4simd15RawComparisonOpEPh
Line
Count
Source
129
84
                            RawComparisonOp op, uint8_t* matches) {
130
84
    const T rhs = literal.get<PT>();
131
84
    simd::raw_compare(values, num_values, rhs, op, matches);
132
84
}
133
134
} // namespace
135
136
788k
VectorizedFnCall::VectorizedFnCall(const TExprNode& node) : VExpr(node) {
137
788k
    _function_name = _fn.name.function_name;
138
788k
}
139
140
Status VectorizedFnCall::prepare(RuntimeState* state, const RowDescriptor& desc,
141
851k
                                 VExprContext* context) {
142
851k
    RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
143
851k
    ColumnsWithTypeAndName argument_template;
144
851k
    argument_template.reserve(_children.size());
145
1.67M
    for (auto child : _children) {
146
1.67M
        if (child->is_literal()) {
147
            // For some functions, he needs some literal columns to derive the return type.
148
798k
            auto literal_node = std::dynamic_pointer_cast<VLiteral>(child);
149
798k
            argument_template.emplace_back(literal_node->get_column_ptr(), child->data_type(),
150
798k
                                           child->expr_name());
151
872k
        } else {
152
872k
            argument_template.emplace_back(nullptr, child->data_type(), child->expr_name());
153
872k
        }
154
1.67M
    }
155
156
851k
    _expr_name = fmt::format("VectorizedFnCall[{}](arguments={},return={})", _fn.name.function_name,
157
851k
                             get_child_names(), _data_type->get_name());
158
851k
    if (_fn.binary_type == TFunctionBinaryType::RPC) {
159
0
        _function = FunctionRPC::create(_fn, argument_template, _data_type);
160
851k
    } else if (_fn.binary_type == TFunctionBinaryType::JAVA_UDF) {
161
529
        if (config::enable_java_support) {
162
529
            if (_fn.is_udtf_function) {
163
                // fake function. it's no use and can't execute.
164
56
                auto builder =
165
56
                        std::make_shared<DefaultFunctionBuilder>(FunctionFake<UDTFImpl>::create());
166
56
                _function = builder->build(argument_template, std::make_shared<DataTypeUInt8>());
167
473
            } else {
168
473
                _function = JavaFunctionCall::create(_fn, argument_template, _data_type);
169
473
            }
170
529
        } else {
171
0
            return Status::InternalError(
172
0
                    "Java UDF is not enabled, you can change be config enable_java_support to true "
173
0
                    "and restart be.");
174
0
        }
175
851k
    } else if (_fn.binary_type == TFunctionBinaryType::PYTHON_UDF) {
176
670
        if (config::enable_python_udf_support) {
177
670
            if (_fn.is_udtf_function) {
178
                // fake function. it's no use and can't execute.
179
                // Python UDTF is executed via PythonUDTFFunction in table function path
180
286
                auto builder =
181
286
                        std::make_shared<DefaultFunctionBuilder>(FunctionFake<UDTFImpl>::create());
182
286
                _function = builder->build(argument_template, std::make_shared<DataTypeUInt8>());
183
384
            } else {
184
384
                _function = PythonFunctionCall::create(_fn, argument_template, _data_type);
185
384
                LOG(INFO) << fmt::format(
186
384
                        "create python function call: {}, runtime version: {}, function code: {}",
187
384
                        _fn.name.function_name, _fn.runtime_version, _fn.function_code);
188
384
            }
189
670
        } else {
190
0
            return Status::InternalError(
191
0
                    "Python UDF is not enabled, you can change be config enable_python_udf_support "
192
0
                    "to true and restart be.");
193
0
        }
194
850k
    } else if (_fn.binary_type == TFunctionBinaryType::AGG_STATE) {
195
761
        DataTypes argument_types;
196
1.11k
        for (auto column : argument_template) {
197
1.11k
            argument_types.emplace_back(column.type);
198
1.11k
        }
199
200
761
        if (match_suffix(_fn.name.function_name, AGG_STATE_SUFFIX)) {
201
761
            if (_data_type->is_nullable()) {
202
0
                return Status::InternalError("State function's return type must be not nullable");
203
0
            }
204
761
            if (_data_type->get_primitive_type() != PrimitiveType::TYPE_AGG_STATE) {
205
0
                return Status::InternalError(
206
0
                        "State function's return type must be agg_state but get {}",
207
0
                        _data_type->get_family_name());
208
0
            }
209
761
            _function = FunctionAggState::create(
210
761
                    argument_types, _data_type,
211
761
                    assert_cast<const DataTypeAggState*>(_data_type.get())->get_nested_function());
212
761
        } else {
213
0
            return Status::InternalError("Function {} is not endwith '_state'", _fn.signature);
214
0
        }
215
849k
    } else {
216
        // get the function. won't prepare function.
217
849k
        _function = SimpleFunctionFactory::instance().get_function(
218
849k
                _fn.name.function_name, argument_template, _data_type,
219
849k
                {.new_version_unix_timestamp = state->query_options().new_version_unix_timestamp,
220
849k
                 .new_version_bitmap_op_count =
221
849k
                         state->query_options().__isset.new_version_bitmap_op_count &&
222
849k
                         state->query_options().new_version_bitmap_op_count},
223
849k
                state->be_exec_version());
224
849k
    }
225
851k
    if (_function == nullptr) {
226
2
        return Status::InternalError("Could not find function {}, arg {} return {} ",
227
2
                                     _fn.name.function_name, get_child_type_names(),
228
2
                                     _data_type->get_name());
229
2
    }
230
851k
    VExpr::register_function_context(state, context);
231
851k
    _function_name = _fn.name.function_name;
232
851k
    _prepare_finished = true;
233
234
851k
    FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
235
851k
    if (fn().__isset.dict_function) {
236
95
        fn_ctx->set_dict_function(fn().dict_function);
237
95
    }
238
851k
    return Status::OK();
239
851k
}
240
241
Status VectorizedFnCall::open(RuntimeState* state, VExprContext* context,
242
2.21M
                              FunctionContext::FunctionStateScope scope) {
243
2.21M
    DCHECK(_prepare_finished);
244
4.24M
    for (auto& i : _children) {
245
4.24M
        RETURN_IF_ERROR(i->open(state, context, scope));
246
4.24M
    }
247
2.21M
    RETURN_IF_ERROR(VExpr::init_function_context(state, context, scope, _function));
248
2.21M
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
249
852k
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
250
852k
    }
251
2.21M
    _open_finished = true;
252
2.21M
    return Status::OK();
253
2.21M
}
254
255
2.23M
void VectorizedFnCall::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
256
2.23M
    VExpr::close_function_context(context, scope, _function);
257
2.23M
    VExpr::close(context, scope);
258
2.23M
}
259
260
13.3k
Status VectorizedFnCall::evaluate_inverted_index(VExprContext* context, uint32_t segment_num_rows) {
261
13.3k
    if (get_num_children() < 1) {
262
        // score() and similar 0-children virtual column functions don't need
263
        // inverted index evaluation; return OK to skip gracefully.
264
61
        return Status::OK();
265
61
    }
266
13.2k
    return _evaluate_inverted_index(context, _function, segment_num_rows);
267
13.3k
}
268
269
36.3k
ZoneMapFilterResult VectorizedFnCall::evaluate_zonemap_filter(const ZoneMapEvalContext& ctx) const {
270
36.3k
    return _function->evaluate_zonemap_filter(ctx, _children);
271
36.3k
}
272
273
123k
bool VectorizedFnCall::can_evaluate_zonemap_filter() const {
274
123k
    return _function != nullptr && !_function->is_blockable() &&
275
123k
           _function->can_evaluate_zonemap_filter(_children);
276
123k
}
277
278
ZoneMapFilterResult VectorizedFnCall::evaluate_dictionary_filter(
279
154k
        const DictionaryEvalContext& ctx) const {
280
154k
    return _function->evaluate_dictionary_filter(ctx, _children);
281
154k
}
282
283
173k
bool VectorizedFnCall::can_evaluate_dictionary_filter() const {
284
173k
    return _function != nullptr && !_function->is_blockable() &&
285
173k
           _function->can_evaluate_dictionary_filter(_children);
286
173k
}
287
288
ZoneMapFilterResult VectorizedFnCall::evaluate_bloom_filter(
289
10
        const BloomFilterEvalContext& ctx) const {
290
10
    return _function->evaluate_bloom_filter(ctx, _children);
291
10
}
292
293
9.72k
bool VectorizedFnCall::can_evaluate_bloom_filter() const {
294
9.73k
    return _function != nullptr && !_function->is_blockable() &&
295
9.72k
           _function->can_evaluate_bloom_filter(_children);
296
9.72k
}
297
298
Status VectorizedFnCall::_do_execute(VExprContext* context, const Block* block,
299
                                     const Selector* selector, size_t count,
300
716k
                                     ColumnPtr& result_column, ColumnPtr* arg_column) const {
301
716k
    if (is_const_and_have_executed()) { // const have executed in open function
302
28.1k
        result_column = get_result_from_const(count);
303
28.1k
        return Status::OK();
304
28.1k
    }
305
688k
    if (fast_execute(context, selector, count, result_column)) {
306
670
        return Status::OK();
307
670
    }
308
688k
    DBUG_EXECUTE_IF("VectorizedFnCall.must_in_slow_path", {
309
688k
        if (get_child(0)->is_slot_ref()) {
310
688k
            auto debug_col_name = DebugPoints::instance()->get_debug_param_or_default<std::string>(
311
688k
                    "VectorizedFnCall.must_in_slow_path", "column_name", "");
312
313
688k
            std::vector<std::string> column_names;
314
688k
            boost::split(column_names, debug_col_name, boost::algorithm::is_any_of(","));
315
316
688k
            auto* column_slot_ref = assert_cast<VSlotRef*>(get_child(0).get());
317
688k
            std::string column_name = column_slot_ref->expr_name();
318
688k
            auto it = std::find(column_names.begin(), column_names.end(), column_name);
319
688k
            if (it == column_names.end()) {
320
688k
                return Status::Error<ErrorCode::INTERNAL_ERROR>(
321
688k
                        "column {} should in slow path while VectorizedFnCall::execute.",
322
688k
                        column_name);
323
688k
            }
324
688k
        }
325
688k
    })
326
688k
    DCHECK(_open_finished || block == nullptr) << debug_string();
327
328
688k
    Block temp_block;
329
688k
    ColumnNumbers args(_children.size());
330
331
1.99M
    for (int i = 0; i < _children.size(); ++i) {
332
1.31M
        ColumnPtr tmp_arg_column;
333
1.31M
        RETURN_IF_ERROR(
334
1.31M
                _children[i]->execute_column(context, block, selector, count, tmp_arg_column));
335
1.31M
        auto arg_type = _children[i]->execute_type(block);
336
1.31M
        temp_block.insert({tmp_arg_column, arg_type, _children[i]->expr_name()});
337
1.31M
        args[i] = i;
338
339
1.31M
        if (arg_column != nullptr && i == 0) {
340
85.5k
            *arg_column = tmp_arg_column;
341
85.5k
        }
342
1.31M
    }
343
344
687k
    uint32_t num_columns_without_result = temp_block.columns();
345
    // prepare a column to save result
346
687k
    temp_block.insert({nullptr, _data_type, _expr_name});
347
348
687k
    DBUG_EXECUTE_IF("VectorizedFnCall.wait_before_execute", {
349
687k
        auto possibility = DebugPoints::instance()->get_debug_param_or_default<double>(
350
687k
                "VectorizedFnCall.wait_before_execute", "possibility", 0);
351
687k
        if (random_bool_slow(possibility)) {
352
687k
            LOG(WARNING) << "VectorizedFnCall::execute sleep 30s";
353
687k
            sleep(30);
354
687k
        }
355
687k
    });
356
357
687k
    RETURN_IF_ERROR(_function->execute(context->fn_context(_fn_context_index), temp_block, args,
358
687k
                                       num_columns_without_result, count));
359
687k
    result_column = temp_block.get_by_position(num_columns_without_result).column;
360
687k
    DCHECK_EQ(result_column->size(), count);
361
687k
    RETURN_IF_ERROR(result_column->column_self_check());
362
687k
    return Status::OK();
363
687k
}
364
365
0
size_t VectorizedFnCall::estimate_memory(const size_t rows) {
366
0
    if (is_const_and_have_executed()) { // const have execute in open function
367
0
        return 0;
368
0
    }
369
370
0
    size_t estimate_size = 0;
371
0
    for (auto& child : _children) {
372
0
        estimate_size += child->estimate_memory(rows);
373
0
    }
374
375
0
    if (_data_type->have_maximum_size_of_value()) {
376
0
        estimate_size += rows * _data_type->get_size_of_value_in_memory();
377
0
    } else {
378
0
        estimate_size += rows * 512; /// FIXME: estimated value...
379
0
    }
380
0
    return estimate_size;
381
0
}
382
383
Status VectorizedFnCall::execute_runtime_filter(VExprContext* context, const Block* block,
384
                                                const uint8_t* __restrict filter, size_t count,
385
                                                ColumnPtr& result_column,
386
85.5k
                                                ColumnPtr* arg_column) const {
387
85.5k
    return _do_execute(context, block, nullptr, count, result_column, arg_column);
388
85.5k
}
389
390
Status VectorizedFnCall::execute_column_impl(VExprContext* context, const Block* block,
391
                                             const Selector* selector, size_t count,
392
631k
                                             ColumnPtr& result_column) const {
393
631k
    return _do_execute(context, block, selector, count, result_column, nullptr);
394
631k
}
395
396
bool VectorizedFnCall::can_execute_on_raw_fixed_values(const DataTypePtr& data_type,
397
10.9k
                                                       int column_id) const {
398
10.9k
    if (data_type == nullptr || !raw_comparison_op(_function_name, false).has_value()) {
399
1.57k
        return false;
400
1.57k
    }
401
9.32k
    auto slot_literal = expr_zonemap::extract_slot_and_literal(_children);
402
9.33k
    if (!slot_literal.has_value() || slot_literal->slot_index != column_id ||
403
9.33k
        slot_literal->literal.is_null()) {
404
2
        return false;
405
2
    }
406
9.32k
    const auto raw_type = remove_nullable(data_type);
407
9.32k
    if (!remove_nullable(slot_literal->slot_type)->equals(*raw_type) ||
408
9.33k
        !remove_nullable(slot_literal->literal_type)->equals(*raw_type)) {
409
2
        return false;
410
2
    }
411
9.32k
    const auto primitive_type = raw_type->get_primitive_type();
412
9.32k
    return primitive_type == TYPE_INT || primitive_type == TYPE_BIGINT ||
413
9.32k
           primitive_type == TYPE_FLOAT || primitive_type == TYPE_DOUBLE;
414
9.32k
}
415
416
Status VectorizedFnCall::execute_on_raw_fixed_values(const uint8_t* values, size_t num_values,
417
                                                     size_t value_width,
418
                                                     const DataTypePtr& data_type, int column_id,
419
2.09k
                                                     uint8_t* matches) const {
420
2.09k
    if (!can_execute_on_raw_fixed_values(data_type, column_id)) {
421
0
        return Status::NotSupported("Expression {} cannot evaluate raw fixed-width values",
422
0
                                    expr_name());
423
0
    }
424
2.09k
    DORIS_CHECK(values != nullptr || num_values == 0);
425
2.09k
    DORIS_CHECK(matches != nullptr || num_values == 0);
426
2.09k
    const auto slot_literal = expr_zonemap::extract_slot_and_literal(_children);
427
2.09k
    DORIS_CHECK(slot_literal.has_value());
428
2.09k
    const auto op = raw_comparison_op(_function_name, slot_literal->literal_on_left);
429
2.09k
    DORIS_CHECK(op.has_value());
430
2.09k
    const auto primitive_type = remove_nullable(data_type)->get_primitive_type();
431
2.09k
    const size_t expected_width = primitive_type == TYPE_INT || primitive_type == TYPE_FLOAT
432
2.09k
                                          ? sizeof(uint32_t)
433
2.09k
                                          : sizeof(uint64_t);
434
2.09k
    if (value_width != expected_width) {
435
0
        return Status::Corruption("Raw expression width {} does not match expected {}", value_width,
436
0
                                  expected_width);
437
0
    }
438
2.09k
    switch (primitive_type) {
439
1.87k
    case TYPE_INT:
440
1.87k
        execute_raw_comparison<int32_t, TYPE_INT>(values, num_values, slot_literal->literal, *op,
441
1.87k
                                                  matches);
442
1.87k
        break;
443
123
    case TYPE_BIGINT:
444
123
        execute_raw_comparison<int64_t, TYPE_BIGINT>(values, num_values, slot_literal->literal, *op,
445
123
                                                     matches);
446
123
        break;
447
8
    case TYPE_FLOAT:
448
8
        execute_raw_comparison<float, TYPE_FLOAT>(values, num_values, slot_literal->literal, *op,
449
8
                                                  matches);
450
8
        break;
451
84
    case TYPE_DOUBLE:
452
84
        execute_raw_comparison<double, TYPE_DOUBLE>(values, num_values, slot_literal->literal, *op,
453
84
                                                    matches);
454
84
        break;
455
0
    default:
456
0
        __builtin_unreachable();
457
2.09k
    }
458
2.09k
    return Status::OK();
459
2.09k
}
460
461
391k
const std::string& VectorizedFnCall::expr_name() const {
462
391k
    return _expr_name;
463
391k
}
464
465
200
std::string VectorizedFnCall::function_name() const {
466
200
    return _function_name;
467
200
}
468
469
616
std::string VectorizedFnCall::debug_string() const {
470
616
    std::stringstream out;
471
616
    out << "VectorizedFn[";
472
616
    out << _expr_name;
473
616
    out << "]{";
474
616
    bool first = true;
475
1.23k
    for (const auto& input_expr : children()) {
476
1.23k
        if (first) {
477
616
            first = false;
478
616
        } else {
479
615
            out << ",";
480
615
        }
481
1.23k
        out << "\n" << input_expr->debug_string();
482
1.23k
    }
483
616
    out << "}";
484
616
    return out.str();
485
616
}
486
487
0
std::string VectorizedFnCall::debug_string(const std::vector<VectorizedFnCall*>& agg_fns) {
488
0
    std::stringstream out;
489
0
    out << "[";
490
0
    for (int i = 0; i < agg_fns.size(); ++i) {
491
0
        out << (i == 0 ? "" : " ") << agg_fns[i]->debug_string();
492
0
    }
493
0
    out << "]";
494
0
    return out.str();
495
0
}
496
497
2.53k
bool VectorizedFnCall::can_push_down_to_index() const {
498
2.53k
    return _function->can_push_down_to_index();
499
2.53k
}
500
501
234k
bool VectorizedFnCall::is_deterministic() const {
502
234k
    static const std::set<std::string> NON_DETERMINISTIC_FUNCTIONS = {
503
234k
            "random", "rand", "random_bytes", "uuid", "uuid_numeric"};
504
234k
    return !NON_DETERMINISTIC_FUNCTIONS.contains(_function_name) && VExpr::is_deterministic();
505
234k
}
506
507
144k
bool VectorizedFnCall::is_safe_to_execute_on_selected_rows() const {
508
144k
    static const std::set<std::string> TOTAL_PREDICATE_FUNCTIONS = {
509
144k
            "eq", "ne", "lt", "le", "gt", "ge", "in", "not_in", "is_null_pred", "is_not_null_pred"};
510
    // Selected-row execution may hide data-dependent errors in rows rejected by an earlier
511
    // predicate. Keep function calls unsafe by default and opt in only operations that are total
512
    // for their input domain; child checks then reject expressions such as gt(mod(x, -1), 0).
513
144k
    return TOTAL_PREDICATE_FUNCTIONS.contains(_function_name) &&
514
144k
           VExpr::is_safe_to_execute_on_selected_rows();
515
144k
}
516
517
0
bool VectorizedFnCall::equals(const VExpr& other) {
518
0
    const auto* other_ptr = dynamic_cast<const VectorizedFnCall*>(&other);
519
0
    if (!other_ptr) {
520
0
        return false;
521
0
    }
522
0
    if (this->_function_name != other_ptr->_function_name) {
523
0
        return false;
524
0
    }
525
0
    if (get_num_children() != other_ptr->get_num_children()) {
526
0
        return false;
527
0
    }
528
0
    for (uint16_t i = 0; i < get_num_children(); i++) {
529
0
        if (!this->get_child(i)->equals(*other_ptr->get_child(i))) {
530
0
            return false;
531
0
        }
532
0
    }
533
0
    return true;
534
0
}
535
536
/*
537
 * For ANN range search we expect a comparison expression (LE/LT/GE/GT) whose left side is either:
538
 *   1) a vector distance function call, or
539
 *   2) a cast/virtual slot that unwraps to the function call when the planner promotes float to
540
 *      double literals.
541
 *
542
 * Visually the logical tree looks like:
543
 *
544
 *   FunctionCall(LE/LT/GE/GT)
545
 *   |----------------
546
 *   |               |
547
 *   |               |
548
 *   VirtualSlotRef* Float32Literal/Float64Literal
549
 *   |
550
 *   |
551
 *   Cast(Float -> Double)*
552
 *   |
553
 *   FunctionCall(distance)
554
 *   |----------------
555
 *   |               |
556
 *   |               |
557
 *   SlotRef         ArrayLiteral/Cast(String as Array<FLOAT>)
558
 *
559
 * Items marked with * are optional and depend on literal types/virtual column usage. The helper
560
 * below normalizes the shape and validates distance function, slot, and constant vector inputs.
561
 */
562
563
void VectorizedFnCall::prepare_ann_range_search(
564
        const doris::VectorSearchUserParams& user_params,
565
14.6k
        segment_v2::AnnRangeSearchRuntime& range_search_runtime, bool& suitable_for_ann_index) {
566
14.6k
    if (!suitable_for_ann_index) {
567
0
        return;
568
0
    }
569
570
14.6k
    if (OPS_FOR_ANN_RANGE_SEARCH.find(this->op()) == OPS_FOR_ANN_RANGE_SEARCH.end()) {
571
11.0k
        suitable_for_ann_index = false;
572
11.0k
        return;
573
11.0k
    }
574
575
3.61k
    auto mark_unsuitable = [&](const std::string& reason) {
576
3.57k
        suitable_for_ann_index = false;
577
18.4E
        VLOG_DEBUG << "ANN range search skipped: " << reason;
578
3.57k
    };
579
580
3.61k
    range_search_runtime.is_le_or_lt =
581
3.61k
            (this->op() == TExprOpcode::LE || this->op() == TExprOpcode::LT);
582
583
3.61k
    DCHECK(_children.size() == 2);
584
585
3.61k
    auto left_child = get_child(0);
586
3.61k
    auto right_child = get_child(1);
587
588
    // ========== Step 1: Check left child - must be a distance function ==========
589
3.61k
    auto get_virtual_expr = [&](const VExprSPtr& expr,
590
4.57k
                                std::shared_ptr<VirtualSlotRef>& slot_ref) -> VExprSPtr {
591
4.57k
        auto virtual_ref = std::dynamic_pointer_cast<VirtualSlotRef>(expr);
592
4.57k
        if (virtual_ref != nullptr) {
593
234
            DCHECK(virtual_ref->get_virtual_column_expr() != nullptr);
594
234
            slot_ref = virtual_ref;
595
234
            return virtual_ref->get_virtual_column_expr();
596
234
        }
597
4.34k
        return expr;
598
4.57k
    };
599
600
3.61k
    std::shared_ptr<VirtualSlotRef> vir_slot_ref;
601
3.61k
    auto normalized_left = get_virtual_expr(left_child, vir_slot_ref);
602
603
    // Try to find the distance function call, it may be wrapped in a Cast(Float->Double)
604
3.61k
    std::shared_ptr<VectorizedFnCall> function_call =
605
3.61k
            std::dynamic_pointer_cast<VectorizedFnCall>(normalized_left);
606
3.61k
    bool has_float_to_double_cast = false;
607
608
3.61k
    if (function_call == nullptr) {
609
        // Check if it's a Cast expression wrapping a function call
610
1.27k
        auto cast_expr = std::dynamic_pointer_cast<VCastExpr>(normalized_left);
611
1.27k
        if (cast_expr == nullptr) {
612
304
            mark_unsuitable("Left child is neither a function call nor a cast expression.");
613
304
            return;
614
304
        }
615
971
        has_float_to_double_cast = true;
616
971
        auto normalized_cast_child = get_virtual_expr(cast_expr->get_child(0), vir_slot_ref);
617
971
        function_call = std::dynamic_pointer_cast<VectorizedFnCall>(normalized_cast_child);
618
971
        if (function_call == nullptr) {
619
920
            mark_unsuitable("Left child of cast is not a function call.");
620
920
            return;
621
920
        }
622
971
    }
623
624
    // Check if it's a supported distance function
625
2.38k
    if (DISTANCE_FUNCS.find(function_call->_function_name) == DISTANCE_FUNCS.end()) {
626
2.34k
        mark_unsuitable(fmt::format("Left child is not a supported distance function: {}",
627
2.34k
                                    function_call->_function_name));
628
2.34k
        return;
629
2.34k
    }
630
631
    // Strip the _approximate suffix to get metric type
632
44
    std::string metric_name = function_call->_function_name;
633
44
    metric_name = metric_name.substr(0, metric_name.size() - 12);
634
44
    range_search_runtime.metric_type = segment_v2::string_to_metric(metric_name);
635
636
    // ========== Step 2: Validate distance function arguments ==========
637
    // Identify the slot ref child and the constant query array child (ArrayLiteral or CAST to array)
638
44
    Int32 idx_of_slot_ref = -1;
639
44
    Int32 idx_of_array_expr = -1;
640
94
    auto classify_child = [&](const VExprSPtr& child, UInt16 index) {
641
94
        if (idx_of_slot_ref == -1 && std::dynamic_pointer_cast<VSlotRef>(child) != nullptr) {
642
47
            idx_of_slot_ref = index;
643
47
            return;
644
47
        }
645
47
        if (idx_of_array_expr == -1 &&
646
47
            (std::dynamic_pointer_cast<VArrayLiteral>(child) != nullptr ||
647
47
             std::dynamic_pointer_cast<VCastExpr>(child) != nullptr)) {
648
40
            idx_of_array_expr = index;
649
40
        }
650
47
    };
651
652
138
    for (UInt16 i = 0; i < function_call->get_num_children(); ++i) {
653
94
        classify_child(function_call->get_child(i), i);
654
94
    }
655
656
47
    if (idx_of_slot_ref == -1 || idx_of_array_expr == -1) {
657
7
        mark_unsuitable("slot ref or array literal/cast is missing.");
658
7
        return;
659
7
    }
660
661
37
    auto slot_ref = std::dynamic_pointer_cast<VSlotRef>(
662
37
            function_call->get_child(static_cast<UInt16>(idx_of_slot_ref)));
663
37
    range_search_runtime.src_col_idx = slot_ref->column_id();
664
37
    range_search_runtime.dst_col_idx = vir_slot_ref == nullptr ? -1 : vir_slot_ref->column_id();
665
666
    // Materialize the constant array expression and validate its shape and types
667
37
    auto array_expr = function_call->get_child(static_cast<UInt16>(idx_of_array_expr));
668
37
    auto extract_result = extract_query_vector(array_expr);
669
37
    if (!extract_result.has_value()) {
670
0
        mark_unsuitable("Failed to extract query vector from constant array expression.");
671
0
        return;
672
0
    }
673
37
    range_search_runtime.query_value = extract_result.value();
674
37
    range_search_runtime.dim = range_search_runtime.query_value->size();
675
676
    // ========== Step 3: Check right child - must be a float/double literal ==========
677
37
    auto right_literal = std::dynamic_pointer_cast<VLiteral>(right_child);
678
37
    if (right_literal == nullptr) {
679
1
        mark_unsuitable("Right child is not a literal.");
680
1
        return;
681
1
    }
682
683
    // Handle nullable literal gracefully - just mark as unsuitable instead of crash
684
36
    if (right_literal->is_nullable()) {
685
0
        mark_unsuitable("Right literal is nullable, not supported for ANN range search.");
686
0
        return;
687
0
    }
688
689
36
    auto right_type = right_literal->get_data_type();
690
36
    PrimitiveType right_primitive = right_type->get_primitive_type();
691
36
    const bool float32_literal = right_primitive == PrimitiveType::TYPE_FLOAT;
692
36
    const bool float64_literal = right_primitive == PrimitiveType::TYPE_DOUBLE;
693
694
36
    if (!float32_literal && !float64_literal) {
695
0
        mark_unsuitable("Right child is not a Float32Literal or Float64Literal.");
696
0
        return;
697
0
    }
698
699
    // Validate consistency: if we have Cast(Float->Double), right must be double literal
700
36
    if (has_float_to_double_cast && !float64_literal) {
701
0
        mark_unsuitable("Cast expression expects double literal on right side.");
702
0
        return;
703
0
    }
704
705
    // Extract radius value
706
36
    auto right_col = right_literal->get_column_ptr()->convert_to_full_column_if_const();
707
36
    if (float32_literal) {
708
7
        const ColumnFloat32* cf32_right = assert_cast<const ColumnFloat32*>(right_col.get());
709
7
        range_search_runtime.radius = cf32_right->get_data()[0];
710
29
    } else {
711
29
        const ColumnFloat64* cf64_right = assert_cast<const ColumnFloat64*>(right_col.get());
712
29
        range_search_runtime.radius = static_cast<float>(cf64_right->get_data()[0]);
713
29
    }
714
715
    // ========== Done: Mark as suitable for ANN range search ==========
716
36
    range_search_runtime.is_ann_range_search = true;
717
36
    range_search_runtime.user_params = user_params;
718
18.4E
    VLOG_DEBUG << fmt::format("Ann range search params: {}", range_search_runtime.to_string());
719
36
    return;
720
36
}
721
722
Status VectorizedFnCall::evaluate_ann_range_search(
723
        const segment_v2::AnnRangeSearchRuntime& range_search_runtime,
724
        const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& cid_to_index_iterators,
725
        const std::vector<ColumnId>& idx_to_cid,
726
        const std::vector<std::unique_ptr<segment_v2::ColumnIterator>>& column_iterators,
727
        size_t rows_of_segment, roaring::Roaring& row_bitmap,
728
        segment_v2::AnnIndexStats& ann_index_stats, bool enable_result_cache,
729
12.1k
        AnnRangeSearchEvaluationResult& evaluation_result) {
730
12.1k
    evaluation_result = {};
731
12.1k
    if (range_search_runtime.is_ann_range_search == false) {
732
12.1k
        return Status::OK();
733
12.1k
    }
734
735
18.4E
    VLOG_DEBUG << fmt::format("Try apply ann range search. Local search params: {}",
736
18.4E
                              range_search_runtime.to_string());
737
18.4E
    size_t origin_num = row_bitmap.cardinality();
738
739
18.4E
    const auto idx_in_block = range_search_runtime.src_col_idx;
740
18.4E
    DCHECK_LT(idx_in_block, idx_to_cid.size())
741
0
            << "idx_in_block: " << idx_in_block << ", idx_to_cid.size(): " << idx_to_cid.size();
742
743
18.4E
    ColumnId src_col_cid = idx_to_cid[idx_in_block];
744
18.4E
    DCHECK(src_col_cid < cid_to_index_iterators.size());
745
18.4E
    segment_v2::IndexIterator* index_iterator = cid_to_index_iterators[src_col_cid].get();
746
18.4E
    if (index_iterator == nullptr) {
747
1
        VLOG_DEBUG << "ANN range search skipped: "
748
0
                   << fmt::format("No index iterator for column cid {}", src_col_cid);
749
1
        ;
750
1
        return Status::OK();
751
1
    }
752
753
18.4E
    segment_v2::AnnIndexIterator* ann_index_iterator =
754
18.4E
            dynamic_cast<segment_v2::AnnIndexIterator*>(index_iterator);
755
18.4E
    if (ann_index_iterator == nullptr) {
756
0
        VLOG_DEBUG << "ANN range search skipped: "
757
0
                   << fmt::format("Column cid {} has no ANN index iterator", src_col_cid);
758
0
        return Status::OK();
759
0
    }
760
18.4E
    DCHECK(ann_index_iterator->get_reader(AnnIndexReaderType::ANN) != nullptr)
761
18.4E
            << "Ann index iterator should have reader. Column cid: " << src_col_cid;
762
18.4E
    std::shared_ptr<AnnIndexReader> ann_index_reader = std::dynamic_pointer_cast<AnnIndexReader>(
763
18.4E
            ann_index_iterator->get_reader(segment_v2::AnnIndexReaderType::ANN));
764
18.4E
    DCHECK(ann_index_reader != nullptr)
765
18.4E
            << "Ann index reader should not be null. Column cid: " << src_col_cid;
766
    // Check if metrics type is match.
767
18.4E
    if (ann_index_reader->get_metric_type() != range_search_runtime.metric_type) {
768
0
        VLOG_DEBUG << "ANN range search skipped: "
769
0
                   << fmt::format("Metric type mismatch. Index={} Query={}",
770
0
                                  segment_v2::metric_to_string(ann_index_reader->get_metric_type()),
771
0
                                  segment_v2::metric_to_string(range_search_runtime.metric_type));
772
0
        return Status::OK();
773
0
    }
774
775
    // Check dimension if available (>0)
776
18.4E
    const size_t index_dim = ann_index_reader->get_dimension();
777
18.4E
    if (index_dim > 0 && index_dim != range_search_runtime.dim) {
778
8
        return Status::InvalidArgument(
779
8
                "Ann range search query dimension {} does not match index dimension {}",
780
8
                range_search_runtime.dim, index_dim);
781
8
    }
782
783
18.4E
    const auto& user_params = range_search_runtime.user_params;
784
18.4E
    if (user_params.should_fallback_ann_index_by_small_candidate(origin_num, rows_of_segment)) {
785
0
        VLOG_DEBUG << fmt::format(
786
0
                "Ann range search input rows {} reach small candidate threshold, "
787
0
                "rows_of_segment: {}, absolute_threshold: {}, percent_threshold: {}, "
788
0
                "will not use ann index to filter",
789
0
                origin_num, rows_of_segment, user_params.ann_index_candidate_rows_threshold,
790
0
                user_params.ann_index_candidate_rows_percent_threshold);
791
0
        ann_index_stats.fall_back_brute_force_cnt += 1;
792
0
        ann_index_stats.range_fallback_by_small_candidate_cnt += 1;
793
0
        ann_index_stats.range_fallback_small_candidate_rows += origin_num;
794
0
        return Status::OK();
795
0
    }
796
797
18.4E
    auto stats = std::make_unique<segment_v2::AnnIndexStats>();
798
    // Track load index timing
799
18.4E
    {
800
18.4E
        SCOPED_TIMER(&(stats->load_index_costs_ns));
801
18.4E
        if (!ann_index_iterator->try_load_index()) {
802
2
            VLOG_DEBUG << "ANN range search skipped: "
803
0
                       << fmt::format("Failed to load ANN index for column cid {}", src_col_cid);
804
2
            ann_index_stats.fall_back_brute_force_cnt += 1;
805
2
            return Status::OK();
806
2
        }
807
18.4E
        double load_costs_ms = static_cast<double>(stats->load_index_costs_ns.value()) / 1000000.0;
808
18.4E
        DorisMetrics::instance()->ann_index_load_costs_ms->increment(
809
18.4E
                static_cast<int64_t>(load_costs_ms));
810
18.4E
    }
811
812
0
    AnnRangeSearchParams params = range_search_runtime.to_range_search_params();
813
814
18.4E
    params.roaring = &row_bitmap;
815
18.4E
    params.enable_result_cache = enable_result_cache;
816
18.4E
    DCHECK(params.roaring != nullptr);
817
18.4E
    DCHECK(params.query_value != nullptr);
818
18.4E
    segment_v2::AnnRangeSearchResult result;
819
18.4E
    RETURN_IF_ERROR(ann_index_iterator->range_search(params, range_search_runtime.user_params,
820
18.4E
                                                     &result, stats.get()));
821
822
18.4E
#ifndef NDEBUG
823
18.4E
    if (range_search_runtime.is_le_or_lt == false &&
824
18.4E
        ann_index_reader->get_metric_type() == AnnIndexMetric::L2) {
825
7
        DCHECK(result.distance == nullptr) << "Should not have distance";
826
7
    }
827
18.4E
    if (range_search_runtime.is_le_or_lt == true &&
828
18.4E
        ann_index_reader->get_metric_type() == AnnIndexMetric::IP) {
829
4
        DCHECK(result.distance == nullptr);
830
4
    }
831
18.4E
#endif
832
18.4E
    DCHECK(result.roaring != nullptr);
833
18.4E
    row_bitmap = *result.roaring;
834
835
    // Process virtual column
836
18.4E
    bool dist_fulfilled = false;
837
18.4E
    if (range_search_runtime.dst_col_idx >= 0) {
838
        // Prepare materialization if we can use result from index.
839
        // Typical situation: range search and operator is LE or LT.
840
4
        if (result.distance != nullptr) {
841
2
            DCHECK(result.row_ids != nullptr);
842
2
            ColumnId dst_col_cid = idx_to_cid[range_search_runtime.dst_col_idx];
843
2
            DCHECK(dst_col_cid < column_iterators.size());
844
2
            DCHECK(column_iterators[dst_col_cid] != nullptr);
845
2
            segment_v2::ColumnIterator* column_iterator = column_iterators[dst_col_cid].get();
846
2
            DCHECK(column_iterator != nullptr);
847
2
            segment_v2::VirtualColumnIterator* virtual_column_iterator =
848
2
                    dynamic_cast<segment_v2::VirtualColumnIterator*>(column_iterator);
849
2
            DCHECK(virtual_column_iterator != nullptr);
850
            // Now convert distance to column
851
2
            size_t size = result.roaring->cardinality();
852
2
            auto distance_col = ColumnFloat32::create(size);
853
2
            const float* src = result.distance.get();
854
2
            float* dst = distance_col->get_data().data();
855
15
            for (size_t i = 0; i < size; ++i) {
856
13
                dst[i] = src[i];
857
13
            }
858
2
            virtual_column_iterator->prepare_materialization(std::move(distance_col),
859
2
                                                             std::move(result.row_ids));
860
2
            dist_fulfilled = true;
861
2
        } else {
862
            // Whether the ANN index should have produced distance depends on metric and operator:
863
            //  - L2: distance is produced for LE/LT; not produced for GE/GT
864
            //  - IP: distance is produced for GE/GT; not produced for LE/LT
865
2
#ifndef NDEBUG
866
2
            const bool should_have_distance =
867
2
                    (range_search_runtime.is_le_or_lt &&
868
2
                     range_search_runtime.metric_type == AnnIndexMetric::L2) ||
869
2
                    (!range_search_runtime.is_le_or_lt &&
870
2
                     range_search_runtime.metric_type == AnnIndexMetric::IP);
871
            // If we expected distance but didn't get it, assert in debug to catch logic errors.
872
2
            DCHECK(!should_have_distance) << "Expected distance from ANN index but got none";
873
2
#endif
874
2
        }
875
18.4E
    } else {
876
        // Dest is not virtual column.
877
18.4E
        dist_fulfilled = true;
878
18.4E
    }
879
880
18.4E
    evaluation_result.executed = true;
881
18.4E
    evaluation_result.dist_fulfilled = dist_fulfilled;
882
18.4E
    VLOG_DEBUG << fmt::format(
883
18.4E
            "Ann range search filtered {} rows, origin {} rows, virtual column is full-filled: {}",
884
18.4E
            origin_num - row_bitmap.cardinality(), origin_num, dist_fulfilled);
885
886
18.4E
    ann_index_stats = *stats;
887
18.4E
    return Status::OK();
888
18.4E
}
889
890
1.30M
double VectorizedFnCall::execute_cost() const {
891
1.30M
    if (!_function) {
892
0
        throw Exception(
893
0
                Status::InternalError("Function is null in expression: {}", this->debug_string()));
894
0
    }
895
1.30M
    double cost = _function->execute_cost();
896
2.61M
    for (const auto& child : _children) {
897
2.61M
        cost += child->execute_cost();
898
2.61M
    }
899
1.30M
    return cost;
900
1.30M
}
901
902
} // namespace doris