Coverage Report

Created: 2026-07-07 23:24

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
183
VectorizedFnCall::VectorizedFnCall(const TExprNode& node) : VExpr(node) {
85
183
    _function_name = _fn.name.function_name;
86
183
}
87
88
Status VectorizedFnCall::prepare(RuntimeState* state, const RowDescriptor& desc,
89
160
                                 VExprContext* context) {
90
160
    RETURN_IF_ERROR_OR_PREPARED(VExpr::prepare(state, desc, context));
91
160
    ColumnsWithTypeAndName argument_template;
92
160
    argument_template.reserve(_children.size());
93
302
    for (auto child : _children) {
94
302
        if (child->is_literal()) {
95
            // For some functions, he needs some literal columns to derive the return type.
96
117
            auto literal_node = std::dynamic_pointer_cast<VLiteral>(child);
97
117
            argument_template.emplace_back(literal_node->get_column_ptr(), child->data_type(),
98
117
                                           child->expr_name());
99
185
        } else {
100
185
            argument_template.emplace_back(nullptr, child->data_type(), child->expr_name());
101
185
        }
102
302
    }
103
104
160
    _expr_name = fmt::format("VectorizedFnCall[{}](arguments={},return={})", _fn.name.function_name,
105
160
                             get_child_names(), _data_type->get_name());
106
160
    if (_fn.binary_type == TFunctionBinaryType::RPC) {
107
0
        _function = FunctionRPC::create(_fn, argument_template, _data_type);
108
160
    } else if (_fn.binary_type == TFunctionBinaryType::JAVA_UDF) {
109
0
        if (config::enable_java_support) {
110
0
            if (_fn.is_udtf_function) {
111
                // fake function. it's no use and can't execute.
112
0
                auto builder =
113
0
                        std::make_shared<DefaultFunctionBuilder>(FunctionFake<UDTFImpl>::create());
114
0
                _function = builder->build(argument_template, std::make_shared<DataTypeUInt8>());
115
0
            } else {
116
0
                _function = JavaFunctionCall::create(_fn, argument_template, _data_type);
117
0
            }
118
0
        } 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
160
    } else if (_fn.binary_type == TFunctionBinaryType::PYTHON_UDF) {
124
0
        if (config::enable_python_udf_support) {
125
0
            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
0
                auto builder =
129
0
                        std::make_shared<DefaultFunctionBuilder>(FunctionFake<UDTFImpl>::create());
130
0
                _function = builder->build(argument_template, std::make_shared<DataTypeUInt8>());
131
0
            } else {
132
0
                _function = PythonFunctionCall::create(_fn, argument_template, _data_type);
133
0
                LOG(INFO) << fmt::format(
134
0
                        "create python function call: {}, runtime version: {}, function code: {}",
135
0
                        _fn.name.function_name, _fn.runtime_version, _fn.function_code);
136
0
            }
137
0
        } 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
160
    } else if (_fn.binary_type == TFunctionBinaryType::AGG_STATE) {
143
0
        DataTypes argument_types;
144
0
        for (auto column : argument_template) {
145
0
            argument_types.emplace_back(column.type);
146
0
        }
147
148
0
        if (match_suffix(_fn.name.function_name, AGG_STATE_SUFFIX)) {
149
0
            if (_data_type->is_nullable()) {
150
0
                return Status::InternalError("State function's return type must be not nullable");
151
0
            }
152
0
            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
0
            _function = FunctionAggState::create(
158
0
                    argument_types, _data_type,
159
0
                    assert_cast<const DataTypeAggState*>(_data_type.get())->get_nested_function());
160
0
        } else {
161
0
            return Status::InternalError("Function {} is not endwith '_state'", _fn.signature);
162
0
        }
163
160
    } else {
164
        // get the function. won't prepare function.
165
160
        _function = SimpleFunctionFactory::instance().get_function(
166
160
                _fn.name.function_name, argument_template, _data_type,
167
160
                {.new_version_unix_timestamp = state->query_options().new_version_unix_timestamp},
168
160
                state->be_exec_version());
169
160
    }
170
160
    if (_function == nullptr) {
171
0
        return Status::InternalError("Could not find function {}, arg {} return {} ",
172
0
                                     _fn.name.function_name, get_child_type_names(),
173
0
                                     _data_type->get_name());
174
0
    }
175
160
    VExpr::register_function_context(state, context);
176
160
    _function_name = _fn.name.function_name;
177
160
    _prepare_finished = true;
178
179
160
    FunctionContext* fn_ctx = context->fn_context(_fn_context_index);
180
160
    if (fn().__isset.dict_function) {
181
0
        fn_ctx->set_dict_function(fn().dict_function);
182
0
    }
183
160
    return Status::OK();
184
160
}
185
186
Status VectorizedFnCall::open(RuntimeState* state, VExprContext* context,
187
157
                              FunctionContext::FunctionStateScope scope) {
188
157
    DCHECK(_prepare_finished);
189
286
    for (auto& i : _children) {
190
286
        RETURN_IF_ERROR(i->open(state, context, scope));
191
286
    }
192
157
    RETURN_IF_ERROR(VExpr::init_function_context(state, context, scope, _function));
193
157
    if (scope == FunctionContext::FRAGMENT_LOCAL) {
194
114
        RETURN_IF_ERROR(VExpr::get_const_col(context, nullptr));
195
114
    }
196
157
    _open_finished = true;
197
157
    return Status::OK();
198
157
}
199
200
252
void VectorizedFnCall::close(VExprContext* context, FunctionContext::FunctionStateScope scope) {
201
252
    VExpr::close_function_context(context, scope, _function);
202
252
    VExpr::close(context, scope);
203
252
}
204
205
18
Status VectorizedFnCall::evaluate_inverted_index(VExprContext* context, uint32_t segment_num_rows) {
206
18
    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
0
        return Status::OK();
210
0
    }
211
18
    return _evaluate_inverted_index(context, _function, segment_num_rows);
212
18
}
213
214
41
ZoneMapFilterResult VectorizedFnCall::evaluate_zonemap_filter(const ZoneMapEvalContext& ctx) const {
215
41
    return _function->evaluate_zonemap_filter(ctx, _children);
216
41
}
217
218
149
bool VectorizedFnCall::can_evaluate_zonemap_filter() const {
219
149
    return _function != nullptr && !_function->is_blockable() &&
220
149
           _function->can_evaluate_zonemap_filter(_children);
221
149
}
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
14
bool VectorizedFnCall::can_evaluate_dictionary_filter() const {
229
14
    return _function != nullptr && !_function->is_blockable() &&
230
14
           _function->can_evaluate_dictionary_filter(_children);
231
14
}
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
14
bool VectorizedFnCall::can_evaluate_bloom_filter() const {
239
14
    return _function != nullptr && !_function->is_blockable() &&
240
14
           _function->can_evaluate_bloom_filter(_children);
241
14
}
242
243
Status VectorizedFnCall::_do_execute(VExprContext* context, const Block* block,
244
                                     const Selector* selector, size_t count,
245
92
                                     ColumnPtr& result_column, ColumnPtr* arg_column) const {
246
92
    if (is_const_and_have_executed()) { // const have executed in open function
247
0
        result_column = get_result_from_const(count);
248
0
        return Status::OK();
249
0
    }
250
92
    if (fast_execute(context, selector, count, result_column)) {
251
0
        return Status::OK();
252
0
    }
253
92
    DBUG_EXECUTE_IF("VectorizedFnCall.must_in_slow_path", {
254
92
        if (get_child(0)->is_slot_ref()) {
255
92
            auto debug_col_name = DebugPoints::instance()->get_debug_param_or_default<std::string>(
256
92
                    "VectorizedFnCall.must_in_slow_path", "column_name", "");
257
258
92
            std::vector<std::string> column_names;
259
92
            boost::split(column_names, debug_col_name, boost::algorithm::is_any_of(","));
260
261
92
            auto* column_slot_ref = assert_cast<VSlotRef*>(get_child(0).get());
262
92
            std::string column_name = column_slot_ref->expr_name();
263
92
            auto it = std::find(column_names.begin(), column_names.end(), column_name);
264
92
            if (it == column_names.end()) {
265
92
                return Status::Error<ErrorCode::INTERNAL_ERROR>(
266
92
                        "column {} should in slow path while VectorizedFnCall::execute.",
267
92
                        column_name);
268
92
            }
269
92
        }
270
92
    })
271
92
    DCHECK(_open_finished || block == nullptr) << debug_string();
272
273
92
    Block temp_block;
274
92
    ColumnNumbers args(_children.size());
275
276
272
    for (int i = 0; i < _children.size(); ++i) {
277
180
        ColumnPtr tmp_arg_column;
278
180
        RETURN_IF_ERROR(
279
180
                _children[i]->execute_column(context, block, selector, count, tmp_arg_column));
280
180
        auto arg_type = _children[i]->execute_type(block);
281
180
        temp_block.insert({tmp_arg_column, arg_type, _children[i]->expr_name()});
282
180
        args[i] = i;
283
284
180
        if (arg_column != nullptr && i == 0) {
285
0
            *arg_column = tmp_arg_column;
286
0
        }
287
180
    }
288
289
92
    uint32_t num_columns_without_result = temp_block.columns();
290
    // prepare a column to save result
291
92
    temp_block.insert({nullptr, _data_type, _expr_name});
292
293
92
    DBUG_EXECUTE_IF("VectorizedFnCall.wait_before_execute", {
294
92
        auto possibility = DebugPoints::instance()->get_debug_param_or_default<double>(
295
92
                "VectorizedFnCall.wait_before_execute", "possibility", 0);
296
92
        if (random_bool_slow(possibility)) {
297
92
            LOG(WARNING) << "VectorizedFnCall::execute sleep 30s";
298
92
            sleep(30);
299
92
        }
300
92
    });
301
302
92
    RETURN_IF_ERROR(_function->execute(context->fn_context(_fn_context_index), temp_block, args,
303
92
                                       num_columns_without_result, count));
304
92
    result_column = temp_block.get_by_position(num_columns_without_result).column;
305
92
    DCHECK_EQ(result_column->size(), count);
306
92
    RETURN_IF_ERROR(result_column->column_self_check());
307
92
    return Status::OK();
308
92
}
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
0
                                                ColumnPtr* arg_column) const {
332
0
    return _do_execute(context, block, nullptr, count, result_column, arg_column);
333
0
}
334
335
Status VectorizedFnCall::execute_column_impl(VExprContext* context, const Block* block,
336
                                             const Selector* selector, size_t count,
337
92
                                             ColumnPtr& result_column) const {
338
92
    return _do_execute(context, block, selector, count, result_column, nullptr);
339
92
}
340
341
62
const std::string& VectorizedFnCall::expr_name() const {
342
62
    return _expr_name;
343
62
}
344
345
6
std::string VectorizedFnCall::function_name() const {
346
6
    return _function_name;
347
6
}
348
349
4
std::string VectorizedFnCall::debug_string() const {
350
4
    std::stringstream out;
351
4
    out << "VectorizedFn[";
352
4
    out << _expr_name;
353
4
    out << "]{";
354
4
    bool first = true;
355
4
    for (const auto& input_expr : children()) {
356
4
        if (first) {
357
2
            first = false;
358
2
        } else {
359
2
            out << ",";
360
2
        }
361
4
        out << "\n" << input_expr->debug_string();
362
4
    }
363
4
    out << "}";
364
4
    return out.str();
365
4
}
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
0
bool VectorizedFnCall::can_push_down_to_index() const {
378
0
    return _function->can_push_down_to_index();
379
0
}
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
7
        segment_v2::AnnRangeSearchRuntime& range_search_runtime, bool& suitable_for_ann_index) {
430
7
    if (!suitable_for_ann_index) {
431
0
        return;
432
0
    }
433
434
7
    if (OPS_FOR_ANN_RANGE_SEARCH.find(this->op()) == OPS_FOR_ANN_RANGE_SEARCH.end()) {
435
0
        suitable_for_ann_index = false;
436
0
        return;
437
0
    }
438
439
7
    auto mark_unsuitable = [&](const std::string& reason) {
440
1
        suitable_for_ann_index = false;
441
1
        VLOG_DEBUG << "ANN range search skipped: " << reason;
442
1
    };
443
444
7
    range_search_runtime.is_le_or_lt =
445
7
            (this->op() == TExprOpcode::LE || this->op() == TExprOpcode::LT);
446
447
7
    DCHECK(_children.size() == 2);
448
449
7
    auto left_child = get_child(0);
450
7
    auto right_child = get_child(1);
451
452
    // ========== Step 1: Check left child - must be a distance function ==========
453
7
    auto get_virtual_expr = [&](const VExprSPtr& expr,
454
7
                                std::shared_ptr<VirtualSlotRef>& slot_ref) -> VExprSPtr {
455
7
        auto virtual_ref = std::dynamic_pointer_cast<VirtualSlotRef>(expr);
456
7
        if (virtual_ref != nullptr) {
457
7
            DCHECK(virtual_ref->get_virtual_column_expr() != nullptr);
458
7
            slot_ref = virtual_ref;
459
7
            return virtual_ref->get_virtual_column_expr();
460
7
        }
461
0
        return expr;
462
7
    };
463
464
7
    std::shared_ptr<VirtualSlotRef> vir_slot_ref;
465
7
    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
7
    std::shared_ptr<VectorizedFnCall> function_call =
469
7
            std::dynamic_pointer_cast<VectorizedFnCall>(normalized_left);
470
7
    bool has_float_to_double_cast = false;
471
472
7
    if (function_call == nullptr) {
473
        // Check if it's a Cast expression wrapping a function call
474
0
        auto cast_expr = std::dynamic_pointer_cast<VCastExpr>(normalized_left);
475
0
        if (cast_expr == nullptr) {
476
0
            mark_unsuitable("Left child is neither a function call nor a cast expression.");
477
0
            return;
478
0
        }
479
0
        has_float_to_double_cast = true;
480
0
        auto normalized_cast_child = get_virtual_expr(cast_expr->get_child(0), vir_slot_ref);
481
0
        function_call = std::dynamic_pointer_cast<VectorizedFnCall>(normalized_cast_child);
482
0
        if (function_call == nullptr) {
483
0
            mark_unsuitable("Left child of cast is not a function call.");
484
0
            return;
485
0
        }
486
0
    }
487
488
    // Check if it's a supported distance function
489
7
    if (DISTANCE_FUNCS.find(function_call->_function_name) == DISTANCE_FUNCS.end()) {
490
0
        mark_unsuitable(fmt::format("Left child is not a supported distance function: {}",
491
0
                                    function_call->_function_name));
492
0
        return;
493
0
    }
494
495
    // Strip the _approximate suffix to get metric type
496
7
    std::string metric_name = function_call->_function_name;
497
7
    metric_name = metric_name.substr(0, metric_name.size() - 12);
498
7
    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
7
    Int32 idx_of_slot_ref = -1;
503
7
    Int32 idx_of_array_expr = -1;
504
14
    auto classify_child = [&](const VExprSPtr& child, UInt16 index) {
505
14
        if (idx_of_slot_ref == -1 && std::dynamic_pointer_cast<VSlotRef>(child) != nullptr) {
506
7
            idx_of_slot_ref = index;
507
7
            return;
508
7
        }
509
7
        if (idx_of_array_expr == -1 &&
510
7
            (std::dynamic_pointer_cast<VArrayLiteral>(child) != nullptr ||
511
7
             std::dynamic_pointer_cast<VCastExpr>(child) != nullptr)) {
512
7
            idx_of_array_expr = index;
513
7
        }
514
7
    };
515
516
21
    for (UInt16 i = 0; i < function_call->get_num_children(); ++i) {
517
14
        classify_child(function_call->get_child(i), i);
518
14
    }
519
520
7
    if (idx_of_slot_ref == -1 || idx_of_array_expr == -1) {
521
0
        mark_unsuitable("slot ref or array literal/cast is missing.");
522
0
        return;
523
0
    }
524
525
7
    auto slot_ref = std::dynamic_pointer_cast<VSlotRef>(
526
7
            function_call->get_child(static_cast<UInt16>(idx_of_slot_ref)));
527
7
    range_search_runtime.src_col_idx = slot_ref->column_id();
528
7
    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
7
    auto array_expr = function_call->get_child(static_cast<UInt16>(idx_of_array_expr));
532
7
    auto extract_result = extract_query_vector(array_expr);
533
7
    if (!extract_result.has_value()) {
534
0
        mark_unsuitable("Failed to extract query vector from constant array expression.");
535
0
        return;
536
0
    }
537
7
    range_search_runtime.query_value = extract_result.value();
538
7
    range_search_runtime.dim = range_search_runtime.query_value->size();
539
540
    // ========== Step 3: Check right child - must be a float/double literal ==========
541
7
    auto right_literal = std::dynamic_pointer_cast<VLiteral>(right_child);
542
7
    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
6
    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
6
    auto right_type = right_literal->get_data_type();
554
6
    PrimitiveType right_primitive = right_type->get_primitive_type();
555
6
    const bool float32_literal = right_primitive == PrimitiveType::TYPE_FLOAT;
556
6
    const bool float64_literal = right_primitive == PrimitiveType::TYPE_DOUBLE;
557
558
6
    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
6
    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
6
    auto right_col = right_literal->get_column_ptr()->convert_to_full_column_if_const();
571
6
    if (float32_literal) {
572
6
        const ColumnFloat32* cf32_right = assert_cast<const ColumnFloat32*>(right_col.get());
573
6
        range_search_runtime.radius = cf32_right->get_data()[0];
574
6
    } else {
575
0
        const ColumnFloat64* cf64_right = assert_cast<const ColumnFloat64*>(right_col.get());
576
0
        range_search_runtime.radius = static_cast<float>(cf64_right->get_data()[0]);
577
0
    }
578
579
    // ========== Done: Mark as suitable for ANN range search ==========
580
6
    range_search_runtime.is_ann_range_search = true;
581
6
    range_search_runtime.user_params = user_params;
582
6
    VLOG_DEBUG << fmt::format("Ann range search params: {}", range_search_runtime.to_string());
583
6
    return;
584
6
}
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
24
        AnnRangeSearchEvaluationResult& evaluation_result) {
594
24
    evaluation_result = {};
595
24
    if (range_search_runtime.is_ann_range_search == false) {
596
18
        return Status::OK();
597
18
    }
598
599
6
    VLOG_DEBUG << fmt::format("Try apply ann range search. Local search params: {}",
600
0
                              range_search_runtime.to_string());
601
6
    size_t origin_num = row_bitmap.cardinality();
602
603
6
    const auto idx_in_block = range_search_runtime.src_col_idx;
604
6
    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
6
    ColumnId src_col_cid = idx_to_cid[idx_in_block];
608
6
    DCHECK(src_col_cid < cid_to_index_iterators.size());
609
6
    segment_v2::IndexIterator* index_iterator = cid_to_index_iterators[src_col_cid].get();
610
6
    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
5
    segment_v2::AnnIndexIterator* ann_index_iterator =
618
5
            dynamic_cast<segment_v2::AnnIndexIterator*>(index_iterator);
619
5
    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
5
    DCHECK(ann_index_iterator->get_reader(AnnIndexReaderType::ANN) != nullptr)
625
0
            << "Ann index iterator should have reader. Column cid: " << src_col_cid;
626
5
    std::shared_ptr<AnnIndexReader> ann_index_reader = std::dynamic_pointer_cast<AnnIndexReader>(
627
5
            ann_index_iterator->get_reader(segment_v2::AnnIndexReaderType::ANN));
628
5
    DCHECK(ann_index_reader != nullptr)
629
0
            << "Ann index reader should not be null. Column cid: " << src_col_cid;
630
    // Check if metrics type is match.
631
5
    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
5
    const size_t index_dim = ann_index_reader->get_dimension();
641
5
    if (index_dim > 0 && index_dim != range_search_runtime.dim) {
642
1
        return Status::InvalidArgument(
643
1
                "Ann range search query dimension {} does not match index dimension {}",
644
1
                range_search_runtime.dim, index_dim);
645
1
    }
646
647
4
    const auto& user_params = range_search_runtime.user_params;
648
4
    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
4
    auto stats = std::make_unique<segment_v2::AnnIndexStats>();
662
    // Track load index timing
663
4
    {
664
4
        SCOPED_TIMER(&(stats->load_index_costs_ns));
665
4
        if (!ann_index_iterator->try_load_index()) {
666
0
            VLOG_DEBUG << "ANN range search skipped: "
667
0
                       << fmt::format("Failed to load ANN index for column cid {}", src_col_cid);
668
0
            ann_index_stats.fall_back_brute_force_cnt += 1;
669
0
            return Status::OK();
670
0
        }
671
4
        double load_costs_ms = static_cast<double>(stats->load_index_costs_ns.value()) / 1000000.0;
672
4
        DorisMetrics::instance()->ann_index_load_costs_ms->increment(
673
4
                static_cast<int64_t>(load_costs_ms));
674
4
    }
675
676
0
    AnnRangeSearchParams params = range_search_runtime.to_range_search_params();
677
678
4
    params.roaring = &row_bitmap;
679
4
    params.enable_result_cache = enable_result_cache;
680
4
    DCHECK(params.roaring != nullptr);
681
4
    DCHECK(params.query_value != nullptr);
682
4
    segment_v2::AnnRangeSearchResult result;
683
4
    RETURN_IF_ERROR(ann_index_iterator->range_search(params, range_search_runtime.user_params,
684
4
                                                     &result, stats.get()));
685
686
4
#ifndef NDEBUG
687
4
    if (range_search_runtime.is_le_or_lt == false &&
688
4
        ann_index_reader->get_metric_type() == AnnIndexMetric::L2) {
689
2
        DCHECK(result.distance == nullptr) << "Should not have distance";
690
2
    }
691
4
    if (range_search_runtime.is_le_or_lt == true &&
692
4
        ann_index_reader->get_metric_type() == AnnIndexMetric::IP) {
693
0
        DCHECK(result.distance == nullptr);
694
0
    }
695
4
#endif
696
4
    DCHECK(result.roaring != nullptr);
697
4
    row_bitmap = *result.roaring;
698
699
    // Process virtual column
700
4
    bool dist_fulfilled = false;
701
4
    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
4
    } else {
740
        // Dest is not virtual column.
741
0
        dist_fulfilled = true;
742
0
    }
743
744
4
    evaluation_result.executed = true;
745
4
    evaluation_result.dist_fulfilled = dist_fulfilled;
746
4
    VLOG_DEBUG << fmt::format(
747
0
            "Ann range search filtered {} rows, origin {} rows, virtual column is full-filled: {}",
748
0
            origin_num - row_bitmap.cardinality(), origin_num, dist_fulfilled);
749
750
4
    ann_index_stats = *stats;
751
4
    return Status::OK();
752
4
}
753
754
4
double VectorizedFnCall::execute_cost() const {
755
4
    if (!_function) {
756
0
        throw Exception(
757
0
                Status::InternalError("Function is null in expression: {}", this->debug_string()));
758
0
    }
759
4
    double cost = _function->execute_cost();
760
8
    for (const auto& child : _children) {
761
8
        cost += child->execute_cost();
762
8
    }
763
4
    return cost;
764
4
}
765
766
} // namespace doris