Coverage Report

Created: 2026-03-12 02:33

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