Coverage Report

Created: 2026-07-28 02:15

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
250
std::optional<RawComparisonOp> raw_comparison_op(std::string_view function_name, bool reverse) {
92
250
    RawComparisonOp op;
93
250
    if (function_name == "eq") {
94
2
        op = RawComparisonOp::EQ;
95
248
    } else if (function_name == "ne") {
96
0
        op = RawComparisonOp::NE;
97
248
    } else if (function_name == "lt") {
98
10
        op = RawComparisonOp::LT;
99
238
    } else if (function_name == "le") {
100
0
        op = RawComparisonOp::LE;
101
238
    } else if (function_name == "gt") {
102
222
        op = RawComparisonOp::GT;
103
222
    } else if (function_name == "ge") {
104
13
        op = RawComparisonOp::GE;
105
13
    } else {
106
3
        return std::nullopt;
107
3
    }
108
247
    if (!reverse || op == RawComparisonOp::EQ || op == RawComparisonOp::NE) {
109
246
        return op;
110
246
    }
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
60
                            RawComparisonOp op, uint8_t* matches) {
130
60
    const T rhs = literal.get<PT>();
131
60
    simd::raw_compare(values, num_values, rhs, op, matches);
132
60
}
vectorized_fn_call.cpp:_ZN5doris12_GLOBAL__N_122execute_raw_comparisonIiLNS_13PrimitiveTypeE5EEEvPKhmRKNS_5FieldENS_4simd15RawComparisonOpEPh
Line
Count
Source
129
57
                            RawComparisonOp op, uint8_t* matches) {
130
57
    const T rhs = literal.get<PT>();
131
57
    simd::raw_compare(values, num_values, rhs, op, matches);
132
57
}
vectorized_fn_call.cpp:_ZN5doris12_GLOBAL__N_122execute_raw_comparisonIlLNS_13PrimitiveTypeE6EEEvPKhmRKNS_5FieldENS_4simd15RawComparisonOpEPh
Line
Count
Source
129
1
                            RawComparisonOp op, uint8_t* matches) {
130
1
    const T rhs = literal.get<PT>();
131
1
    simd::raw_compare(values, num_values, rhs, op, matches);
132
1
}
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
253
VectorizedFnCall::VectorizedFnCall(const TExprNode& node) : VExpr(node) {
137
253
    _function_name = _fn.name.function_name;
138
253
}
139
140
Status VectorizedFnCall::prepare(RuntimeState* state, const RowDescriptor& desc,
141
188
                                 VExprContext* context) {
142
188
    RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
143
188
    ColumnsWithTypeAndName argument_template;
144
188
    argument_template.reserve(_children.size());
145
358
    for (auto child : _children) {
146
358
        if (child->is_literal()) {
147
            // For some functions, he needs some literal columns to derive the return type.
148
134
            auto literal_node = std::dynamic_pointer_cast<VLiteral>(child);
149
134
            argument_template.emplace_back(literal_node->get_column_ptr(), child->data_type(),
150
134
                                           child->expr_name());
151
224
        } else {
152
224
            argument_template.emplace_back(nullptr, child->data_type(), child->expr_name());
153
224
        }
154
358
    }
155
156
188
    _expr_name = fmt::format("VectorizedFnCall[{}](arguments={},return={})", _fn.name.function_name,
157
188
                             get_child_names(), _data_type->get_name());
158
188
    if (_fn.binary_type == TFunctionBinaryType::RPC) {
159
0
        _function = FunctionRPC::create(_fn, argument_template, _data_type);
160
188
    } 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
188
    } 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
188
    } 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
188
    } else {
216
        // get the function. won't prepare function.
217
188
        _function = SimpleFunctionFactory::instance().get_function(
218
188
                _fn.name.function_name, argument_template, _data_type,
219
188
                {.new_version_unix_timestamp = state->query_options().new_version_unix_timestamp,
220
188
                 .new_version_bitmap_op_count =
221
188
                         state->query_options().__isset.new_version_bitmap_op_count &&
222
188
                         state->query_options().new_version_bitmap_op_count},
223
188
                state->be_exec_version());
224
188
    }
225
188
    if (_function == nullptr) {
226
0
        return Status::InternalError("Could not find function {}, arg {} return {} ",
227
0
                                     _fn.name.function_name, get_child_type_names(),
228
0
                                     _data_type->get_name());
229
0
    }
230
188
    VExpr::register_function_context(state, context);
231
188
    _function_name = _fn.name.function_name;
232
188
    _prepare_finished = true;
233
234
188
    FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
235
188
    if (fn().__isset.dict_function) {
236
0
        fn_ctx->set_dict_function(fn().dict_function);
237
0
    }
238
188
    return Status::OK();
239
188
}
240
241
Status VectorizedFnCall::open(RuntimeState* state, VExprContext* context,
242
185
                              FunctionContext::FunctionStateScope scope) {
243
185
    DCHECK(_prepare_finished);
244
342
    for (auto& i : _children) {
245
342
        RETURN_IF_ERROR(i->open(state, context, scope));
246
342
    }
247
185
    RETURN_IF_ERROR(VExpr::init_function_context(state, context, scope, _function));
248
185
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
249
142
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
250
142
    }
251
185
    _open_finished = true;
252
185
    return Status::OK();
253
185
}
254
255
302
void VectorizedFnCall::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
256
302
    VExpr::close_function_context(context, scope, _function);
257
302
    VExpr::close(context, scope);
258
302
}
259
260
18
Status VectorizedFnCall::evaluate_inverted_index(VExprContext* context, uint32_t segment_num_rows) {
261
18
    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
0
        return Status::OK();
265
0
    }
266
18
    return _evaluate_inverted_index(context, _function, segment_num_rows);
267
18
}
268
269
46
ZoneMapFilterResult VectorizedFnCall::evaluate_zonemap_filter(const ZoneMapEvalContext& ctx) const {
270
46
    return _function->evaluate_zonemap_filter(ctx, _children);
271
46
}
272
273
224
bool VectorizedFnCall::can_evaluate_zonemap_filter() const {
274
224
    return _function != nullptr && !_function->is_blockable() &&
275
224
           _function->can_evaluate_zonemap_filter(_children);
276
224
}
277
278
ZoneMapFilterResult VectorizedFnCall::evaluate_dictionary_filter(
279
2
        const DictionaryEvalContext& ctx) const {
280
2
    return _function->evaluate_dictionary_filter(ctx, _children);
281
2
}
282
283
72
bool VectorizedFnCall::can_evaluate_dictionary_filter() const {
284
72
    return _function != nullptr && !_function->is_blockable() &&
285
72
           _function->can_evaluate_dictionary_filter(_children);
286
72
}
287
288
ZoneMapFilterResult VectorizedFnCall::evaluate_bloom_filter(
289
0
        const BloomFilterEvalContext& ctx) const {
290
0
    return _function->evaluate_bloom_filter(ctx, _children);
291
0
}
292
293
31
bool VectorizedFnCall::can_evaluate_bloom_filter() const {
294
31
    return _function != nullptr && !_function->is_blockable() &&
295
31
           _function->can_evaluate_bloom_filter(_children);
296
31
}
297
298
Status VectorizedFnCall::_do_execute(VExprContext* context, const Block* block,
299
                                     const Selector* selector, size_t count,
300
90
                                     ColumnPtr& result_column, ColumnPtr* arg_column) const {
301
90
    if (is_const_and_have_executed()) { // const have executed in open function
302
0
        result_column = get_result_from_const(count);
303
0
        return Status::OK();
304
0
    }
305
90
    if (fast_execute(context, selector, count, result_column)) {
306
0
        return Status::OK();
307
0
    }
308
90
    DBUG_EXECUTE_IF("VectorizedFnCall.must_in_slow_path", {
309
90
        if (get_child(0)->is_slot_ref()) {
310
90
            auto debug_col_name = DebugPoints::instance()->get_debug_param_or_default<std::string>(
311
90
                    "VectorizedFnCall.must_in_slow_path", "column_name", "");
312
313
90
            std::vector<std::string> column_names;
314
90
            boost::split(column_names, debug_col_name, boost::algorithm::is_any_of(","));
315
316
90
            auto* column_slot_ref = assert_cast<VSlotRef*>(get_child(0).get());
317
90
            std::string column_name = column_slot_ref->expr_name();
318
90
            auto it = std::find(column_names.begin(), column_names.end(), column_name);
319
90
            if (it == column_names.end()) {
320
90
                return Status::Error<ErrorCode::INTERNAL_ERROR>(
321
90
                        "column {} should in slow path while VectorizedFnCall::execute.",
322
90
                        column_name);
323
90
            }
324
90
        }
325
90
    })
326
90
    DCHECK(_open_finished || block == nullptr) << debug_string();
327
328
90
    Block temp_block;
329
90
    ColumnNumbers args(_children.size());
330
331
264
    for (int i = 0; i < _children.size(); ++i) {
332
175
        ColumnPtr tmp_arg_column;
333
175
        RETURN_IF_ERROR(
334
175
                _children[i]->execute_column(context, block, selector, count, tmp_arg_column));
335
174
        auto arg_type = _children[i]->execute_type(block);
336
174
        temp_block.insert({tmp_arg_column, arg_type, _children[i]->expr_name()});
337
174
        args[i] = i;
338
339
174
        if (arg_column != nullptr && i == 0) {
340
2
            *arg_column = tmp_arg_column;
341
2
        }
342
174
    }
343
344
89
    uint32_t num_columns_without_result = temp_block.columns();
345
    // prepare a column to save result
346
89
    temp_block.insert({nullptr, _data_type, _expr_name});
347
348
89
    DBUG_EXECUTE_IF("VectorizedFnCall.wait_before_execute", {
349
89
        auto possibility = DebugPoints::instance()->get_debug_param_or_default<double>(
350
89
                "VectorizedFnCall.wait_before_execute", "possibility", 0);
351
89
        if (random_bool_slow(possibility)) {
352
89
            LOG(WARNING) << "VectorizedFnCall::execute sleep 30s";
353
89
            sleep(30);
354
89
        }
355
89
    });
356
357
89
    RETURN_IF_ERROR(_function->execute(context->fn_context(_fn_context_index), temp_block, args,
358
89
                                       num_columns_without_result, count));
359
89
    result_column = temp_block.get_by_position(num_columns_without_result).column;
360
89
    DCHECK_EQ(result_column->size(), count);
361
89
    RETURN_IF_ERROR(result_column->column_self_check());
362
89
    return Status::OK();
363
89
}
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
2
                                                ColumnPtr* arg_column) const {
387
2
    return _do_execute(context, block, nullptr, count, result_column, arg_column);
388
2
}
389
390
Status VectorizedFnCall::execute_column_impl(VExprContext* context, const Block* block,
391
                                             const Selector* selector, size_t count,
392
88
                                             ColumnPtr& result_column) const {
393
88
    return _do_execute(context, block, selector, count, result_column, nullptr);
394
88
}
395
396
bool VectorizedFnCall::can_execute_on_raw_fixed_values(const DataTypePtr& data_type,
397
190
                                                       int column_id) const {
398
190
    if (data_type == nullptr || !raw_comparison_op(_function_name, false).has_value()) {
399
3
        return false;
400
3
    }
401
187
    auto slot_literal = expr_zonemap::extract_slot_and_literal(_children);
402
187
    if (!slot_literal.has_value() || slot_literal->slot_index != column_id ||
403
187
        slot_literal->literal.is_null()) {
404
0
        return false;
405
0
    }
406
187
    const auto raw_type = remove_nullable(data_type);
407
187
    if (!remove_nullable(slot_literal->slot_type)->equals(*raw_type) ||
408
187
        !remove_nullable(slot_literal->literal_type)->equals(*raw_type)) {
409
0
        return false;
410
0
    }
411
187
    const auto primitive_type = raw_type->get_primitive_type();
412
187
    return primitive_type == TYPE_INT || primitive_type == TYPE_BIGINT ||
413
187
           primitive_type == TYPE_FLOAT || primitive_type == TYPE_DOUBLE;
414
187
}
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
60
                                                     uint8_t* matches) const {
420
60
    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
60
    DORIS_CHECK(values != nullptr || num_values == 0);
425
60
    DORIS_CHECK(matches != nullptr || num_values == 0);
426
60
    const auto slot_literal = expr_zonemap::extract_slot_and_literal(_children);
427
60
    DORIS_CHECK(slot_literal.has_value());
428
60
    const auto op = raw_comparison_op(_function_name, slot_literal->literal_on_left);
429
60
    DORIS_CHECK(op.has_value());
430
60
    const auto primitive_type = remove_nullable(data_type)->get_primitive_type();
431
60
    const size_t expected_width = primitive_type == TYPE_INT || primitive_type == TYPE_FLOAT
432
60
                                          ? sizeof(uint32_t)
433
60
                                          : sizeof(uint64_t);
434
60
    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
60
    switch (primitive_type) {
439
57
    case TYPE_INT:
440
57
        execute_raw_comparison<int32_t, TYPE_INT>(values, num_values, slot_literal->literal, *op,
441
57
                                                  matches);
442
57
        break;
443
1
    case TYPE_BIGINT:
444
1
        execute_raw_comparison<int64_t, TYPE_BIGINT>(values, num_values, slot_literal->literal, *op,
445
1
                                                     matches);
446
1
        break;
447
2
    case TYPE_FLOAT:
448
2
        execute_raw_comparison<float, TYPE_FLOAT>(values, num_values, slot_literal->literal, *op,
449
2
                                                  matches);
450
2
        break;
451
0
    case TYPE_DOUBLE:
452
0
        execute_raw_comparison<double, TYPE_DOUBLE>(values, num_values, slot_literal->literal, *op,
453
0
                                                    matches);
454
0
        break;
455
0
    default:
456
0
        __builtin_unreachable();
457
60
    }
458
60
    return Status::OK();
459
60
}
460
461
80
const std::string& VectorizedFnCall::expr_name() const {
462
80
    return _expr_name;
463
80
}
464
465
8
std::string VectorizedFnCall::function_name() const {
466
8
    return _function_name;
467
8
}
468
469
4
std::string VectorizedFnCall::debug_string() const {
470
4
    std::stringstream out;
471
4
    out << "VectorizedFn[";
472
4
    out << _expr_name;
473
4
    out << "]{";
474
4
    bool first = true;
475
4
    for (const auto& input_expr : children()) {
476
4
        if (first) {
477
2
            first = false;
478
2
        } else {
479
2
            out << ",";
480
2
        }
481
4
        out << "\n" << input_expr->debug_string();
482
4
    }
483
4
    out << "}";
484
4
    return out.str();
485
4
}
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
0
bool VectorizedFnCall::can_push_down_to_index() const {
498
0
    return _function->can_push_down_to_index();
499
0
}
500
501
155
bool VectorizedFnCall::is_deterministic() const {
502
155
    static const std::set<std::string> NON_DETERMINISTIC_FUNCTIONS = {
503
155
            "random", "rand", "random_bytes", "uuid", "uuid_numeric"};
504
155
    return !NON_DETERMINISTIC_FUNCTIONS.contains(_function_name) && VExpr::is_deterministic();
505
155
}
506
507
97
bool VectorizedFnCall::is_safe_to_execute_on_selected_rows() const {
508
97
    static const std::set<std::string> TOTAL_PREDICATE_FUNCTIONS = {
509
97
            "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
97
    return TOTAL_PREDICATE_FUNCTIONS.contains(_function_name) &&
514
97
           VExpr::is_safe_to_execute_on_selected_rows();
515
97
}
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
7
        segment_v2::AnnRangeSearchRuntime& range_search_runtime, bool& suitable_for_ann_index) {
566
7
    if (!suitable_for_ann_index) {
567
0
        return;
568
0
    }
569
570
7
    if (OPS_FOR_ANN_RANGE_SEARCH.find(this->op()) == OPS_FOR_ANN_RANGE_SEARCH.end()) {
571
0
        suitable_for_ann_index = false;
572
0
        return;
573
0
    }
574
575
7
    auto mark_unsuitable = [&](const std::string& reason) {
576
1
        suitable_for_ann_index = false;
577
1
        VLOG_DEBUG << "ANN range search skipped: " << reason;
578
1
    };
579
580
7
    range_search_runtime.is_le_or_lt =
581
7
            (this->op() == TExprOpcode::LE || this->op() == TExprOpcode::LT);
582
583
7
    DCHECK(_children.size() == 2);
584
585
7
    auto left_child = get_child(0);
586
7
    auto right_child = get_child(1);
587
588
    // ========== Step 1: Check left child - must be a distance function ==========
589
7
    auto get_virtual_expr = [&](const VExprSPtr& expr,
590
7
                                std::shared_ptr<VirtualSlotRef>& slot_ref) -> VExprSPtr {
591
7
        auto virtual_ref = std::dynamic_pointer_cast<VirtualSlotRef>(expr);
592
7
        if (virtual_ref != nullptr) {
593
7
            DCHECK(virtual_ref->get_virtual_column_expr() != nullptr);
594
7
            slot_ref = virtual_ref;
595
7
            return virtual_ref->get_virtual_column_expr();
596
7
        }
597
0
        return expr;
598
7
    };
599
600
7
    std::shared_ptr<VirtualSlotRef> vir_slot_ref;
601
7
    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
7
    std::shared_ptr<VectorizedFnCall> function_call =
605
7
            std::dynamic_pointer_cast<VectorizedFnCall>(normalized_left);
606
7
    bool has_float_to_double_cast = false;
607
608
7
    if (function_call == nullptr) {
609
        // Check if it's a Cast expression wrapping a function call
610
0
        auto cast_expr = std::dynamic_pointer_cast<VCastExpr>(normalized_left);
611
0
        if (cast_expr == nullptr) {
612
0
            mark_unsuitable("Left child is neither a function call nor a cast expression.");
613
0
            return;
614
0
        }
615
0
        has_float_to_double_cast = true;
616
0
        auto normalized_cast_child = get_virtual_expr(cast_expr->get_child(0), vir_slot_ref);
617
0
        function_call = std::dynamic_pointer_cast<VectorizedFnCall>(normalized_cast_child);
618
0
        if (function_call == nullptr) {
619
0
            mark_unsuitable("Left child of cast is not a function call.");
620
0
            return;
621
0
        }
622
0
    }
623
624
    // Check if it's a supported distance function
625
7
    if (DISTANCE_FUNCS.find(function_call->_function_name) == DISTANCE_FUNCS.end()) {
626
0
        mark_unsuitable(fmt::format("Left child is not a supported distance function: {}",
627
0
                                    function_call->_function_name));
628
0
        return;
629
0
    }
630
631
    // Strip the _approximate suffix to get metric type
632
7
    std::string metric_name = function_call->_function_name;
633
7
    metric_name = metric_name.substr(0, metric_name.size() - 12);
634
7
    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
7
    Int32 idx_of_slot_ref = -1;
639
7
    Int32 idx_of_array_expr = -1;
640
14
    auto classify_child = [&](const VExprSPtr& child, UInt16 index) {
641
14
        if (idx_of_slot_ref == -1 && std::dynamic_pointer_cast<VSlotRef>(child) != nullptr) {
642
7
            idx_of_slot_ref = index;
643
7
            return;
644
7
        }
645
7
        if (idx_of_array_expr == -1 &&
646
7
            (std::dynamic_pointer_cast<VArrayLiteral>(child) != nullptr ||
647
7
             std::dynamic_pointer_cast<VCastExpr>(child) != nullptr)) {
648
7
            idx_of_array_expr = index;
649
7
        }
650
7
    };
651
652
21
    for (UInt16 i = 0; i < function_call->get_num_children(); ++i) {
653
14
        classify_child(function_call->get_child(i), i);
654
14
    }
655
656
7
    if (idx_of_slot_ref == -1 || idx_of_array_expr == -1) {
657
0
        mark_unsuitable("slot ref or array literal/cast is missing.");
658
0
        return;
659
0
    }
660
661
7
    auto slot_ref = std::dynamic_pointer_cast<VSlotRef>(
662
7
            function_call->get_child(static_cast<UInt16>(idx_of_slot_ref)));
663
7
    range_search_runtime.src_col_idx = slot_ref->column_id();
664
7
    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
7
    auto array_expr = function_call->get_child(static_cast<UInt16>(idx_of_array_expr));
668
7
    auto extract_result = extract_query_vector(array_expr);
669
7
    if (!extract_result.has_value()) {
670
0
        mark_unsuitable("Failed to extract query vector from constant array expression.");
671
0
        return;
672
0
    }
673
7
    range_search_runtime.query_value = extract_result.value();
674
7
    range_search_runtime.dim = range_search_runtime.query_value->size();
675
676
    // ========== Step 3: Check right child - must be a float/double literal ==========
677
7
    auto right_literal = std::dynamic_pointer_cast<VLiteral>(right_child);
678
7
    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
6
    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
6
    auto right_type = right_literal->get_data_type();
690
6
    PrimitiveType right_primitive = right_type->get_primitive_type();
691
6
    const bool float32_literal = right_primitive == PrimitiveType::TYPE_FLOAT;
692
6
    const bool float64_literal = right_primitive == PrimitiveType::TYPE_DOUBLE;
693
694
6
    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
6
    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
6
    auto right_col = right_literal->get_column_ptr()->convert_to_full_column_if_const();
707
6
    if (float32_literal) {
708
6
        const ColumnFloat32* cf32_right = assert_cast<const ColumnFloat32*>(right_col.get());
709
6
        range_search_runtime.radius = cf32_right->get_data()[0];
710
6
    } else {
711
0
        const ColumnFloat64* cf64_right = assert_cast<const ColumnFloat64*>(right_col.get());
712
0
        range_search_runtime.radius = static_cast<float>(cf64_right->get_data()[0]);
713
0
    }
714
715
    // ========== Done: Mark as suitable for ANN range search ==========
716
6
    range_search_runtime.is_ann_range_search = true;
717
6
    range_search_runtime.user_params = user_params;
718
6
    VLOG_DEBUG << fmt::format("Ann range search params: {}", range_search_runtime.to_string());
719
6
    return;
720
6
}
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
24
        AnnRangeSearchEvaluationResult& evaluation_result) {
730
24
    evaluation_result = {};
731
24
    if (range_search_runtime.is_ann_range_search == false) {
732
18
        return Status::OK();
733
18
    }
734
735
6
    VLOG_DEBUG << fmt::format("Try apply ann range search. Local search params: {}",
736
0
                              range_search_runtime.to_string());
737
6
    size_t origin_num = row_bitmap.cardinality();
738
739
6
    const auto idx_in_block = range_search_runtime.src_col_idx;
740
6
    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
6
    ColumnId src_col_cid = idx_to_cid[idx_in_block];
744
6
    DCHECK(src_col_cid < cid_to_index_iterators.size());
745
6
    segment_v2::IndexIterator* index_iterator = cid_to_index_iterators[src_col_cid].get();
746
6
    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
5
    segment_v2::AnnIndexIterator* ann_index_iterator =
754
5
            dynamic_cast<segment_v2::AnnIndexIterator*>(index_iterator);
755
5
    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
5
    DCHECK(ann_index_iterator->get_reader(AnnIndexReaderType::ANN) != nullptr)
761
0
            << "Ann index iterator should have reader. Column cid: " << src_col_cid;
762
5
    std::shared_ptr<AnnIndexReader> ann_index_reader = std::dynamic_pointer_cast<AnnIndexReader>(
763
5
            ann_index_iterator->get_reader(segment_v2::AnnIndexReaderType::ANN));
764
5
    DCHECK(ann_index_reader != nullptr)
765
0
            << "Ann index reader should not be null. Column cid: " << src_col_cid;
766
    // Check if metrics type is match.
767
5
    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
5
    const size_t index_dim = ann_index_reader->get_dimension();
777
5
    if (index_dim > 0 && index_dim != range_search_runtime.dim) {
778
1
        return Status::InvalidArgument(
779
1
                "Ann range search query dimension {} does not match index dimension {}",
780
1
                range_search_runtime.dim, index_dim);
781
1
    }
782
783
4
    const auto& user_params = range_search_runtime.user_params;
784
4
    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
4
    auto stats = std::make_unique<segment_v2::AnnIndexStats>();
798
    // Track load index timing
799
4
    {
800
4
        SCOPED_TIMER(&(stats->load_index_costs_ns));
801
4
        if (!ann_index_iterator->try_load_index()) {
802
0
            VLOG_DEBUG << "ANN range search skipped: "
803
0
                       << fmt::format("Failed to load ANN index for column cid {}", src_col_cid);
804
0
            ann_index_stats.fall_back_brute_force_cnt += 1;
805
0
            return Status::OK();
806
0
        }
807
4
        double load_costs_ms = static_cast<double>(stats->load_index_costs_ns.value()) / 1000000.0;
808
4
        DorisMetrics::instance()->ann_index_load_costs_ms->increment(
809
4
                static_cast<int64_t>(load_costs_ms));
810
4
    }
811
812
0
    AnnRangeSearchParams params = range_search_runtime.to_range_search_params();
813
814
4
    params.roaring = &row_bitmap;
815
4
    params.enable_result_cache = enable_result_cache;
816
4
    DCHECK(params.roaring != nullptr);
817
4
    DCHECK(params.query_value != nullptr);
818
4
    segment_v2::AnnRangeSearchResult result;
819
4
    RETURN_IF_ERROR(ann_index_iterator->range_search(params, range_search_runtime.user_params,
820
4
                                                     &result, stats.get()));
821
822
4
#ifndef NDEBUG
823
4
    if (range_search_runtime.is_le_or_lt == false &&
824
4
        ann_index_reader->get_metric_type() == AnnIndexMetric::L2) {
825
2
        DCHECK(result.distance == nullptr) << "Should not have distance";
826
2
    }
827
4
    if (range_search_runtime.is_le_or_lt == true &&
828
4
        ann_index_reader->get_metric_type() == AnnIndexMetric::IP) {
829
0
        DCHECK(result.distance == nullptr);
830
0
    }
831
4
#endif
832
4
    DCHECK(result.roaring != nullptr);
833
4
    row_bitmap = *result.roaring;
834
835
    // Process virtual column
836
4
    bool dist_fulfilled = false;
837
4
    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
4
    } else {
876
        // Dest is not virtual column.
877
0
        dist_fulfilled = true;
878
0
    }
879
880
4
    evaluation_result.executed = true;
881
4
    evaluation_result.dist_fulfilled = dist_fulfilled;
882
4
    VLOG_DEBUG << fmt::format(
883
0
            "Ann range search filtered {} rows, origin {} rows, virtual column is full-filled: {}",
884
0
            origin_num - row_bitmap.cardinality(), origin_num, dist_fulfilled);
885
886
4
    ann_index_stats = *stats;
887
4
    return Status::OK();
888
4
}
889
890
4
double VectorizedFnCall::execute_cost() const {
891
4
    if (!_function) {
892
0
        throw Exception(
893
0
                Status::InternalError("Function is null in expression: {}", this->debug_string()));
894
0
    }
895
4
    double cost = _function->execute_cost();
896
8
    for (const auto& child : _children) {
897
8
        cost += child->execute_cost();
898
8
    }
899
4
    return cost;
900
4
}
901
902
} // namespace doris