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