Coverage Report

Created: 2026-07-24 23:23

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