Coverage Report

Created: 2026-07-06 12:17

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