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/vexpr_context.h" |
19 | | |
20 | | #include <algorithm> |
21 | | #include <cstdint> |
22 | | #include <memory> |
23 | | #include <string> |
24 | | #include <utility> |
25 | | |
26 | | #include "common/compiler_util.h" // IWYU pragma: keep |
27 | | #include "common/exception.h" |
28 | | #include "common/logging.h" |
29 | | #include "common/status.h" |
30 | | #include "core/block/column_numbers.h" |
31 | | #include "core/block/column_with_type_and_name.h" |
32 | | #include "core/block/columns_with_type_and_name.h" |
33 | | #include "core/column/column.h" |
34 | | #include "core/column/column_const.h" |
35 | | #include "core/column/column_nullable.h" |
36 | | #include "exec/common/util.hpp" |
37 | | #include "exprs/function_context.h" |
38 | | #include "exprs/lambda_function/lambda_execution_context.h" |
39 | | #include "exprs/vexpr.h" |
40 | | #include "runtime/runtime_state.h" |
41 | | #include "runtime/thread_context.h" |
42 | | #include "storage/olap_common.h" |
43 | | #include "storage/segment/column_reader.h" |
44 | | #include "util/simd/bits.h" |
45 | | #include "util/time.h" |
46 | | |
47 | | namespace doris { |
48 | | class RowDescriptor; |
49 | | } // namespace doris |
50 | | |
51 | | namespace doris { |
52 | | |
53 | 31.3M | VExprContext::VExprContext(VExprSPtr expr) : _root(std::move(expr)) {} |
54 | | |
55 | 31.3M | VExprContext::~VExprContext() { |
56 | | // In runtime filter, only create expr context to get expr root, will not call |
57 | | // prepare or open, so that it is not need to call close. And call close may core |
58 | | // because the function context in expr is not set. |
59 | 31.3M | if (!_prepared || !_opened) { |
60 | 820k | return; |
61 | 820k | } |
62 | 30.5M | try { |
63 | 30.5M | close(); |
64 | 30.5M | } catch (const Exception& e) { |
65 | 0 | LOG(WARNING) << "Exception occurs when expr context deconstruct: " << e.to_string(); |
66 | 0 | } |
67 | 30.5M | } |
68 | | |
69 | 21.3k | LambdaExecutionContext& VExprContext::lambda_execution_context() { |
70 | 21.3k | if (!_lambda_execution_context) { |
71 | 2.82k | _lambda_execution_context = std::make_unique<LambdaExecutionContext>(); |
72 | 2.82k | } |
73 | 21.3k | return *_lambda_execution_context; |
74 | 21.3k | } |
75 | | |
76 | 2.42M | Status VExprContext::execute(Block* block, int* result_column_id) { |
77 | 2.42M | Status st; |
78 | 2.42M | RETURN_IF_CATCH_EXCEPTION({ |
79 | 2.42M | st = _root->execute(this, block, result_column_id); |
80 | 2.42M | _last_result_column_id = *result_column_id; |
81 | | // We should first check the status, as some expressions might incorrectly set result_column_id, even if the st is not ok. |
82 | 2.42M | if (st.ok() && _last_result_column_id != -1) { |
83 | 2.42M | block->get_by_position(*result_column_id).column->sanity_check(); |
84 | 2.42M | RETURN_IF_ERROR( |
85 | 2.42M | block->get_by_position(*result_column_id).check_type_and_column_match()); |
86 | 2.42M | } |
87 | 2.42M | }); |
88 | 2.42M | return st; |
89 | 2.42M | } |
90 | | |
91 | 2.81M | Status VExprContext::execute(const Block* block, ColumnPtr& result_column) { |
92 | 2.81M | Status st; |
93 | 2.81M | RETURN_IF_CATCH_EXCEPTION( |
94 | 2.81M | { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); }); |
95 | 2.81M | return st; |
96 | 2.81M | } |
97 | | |
98 | 42.7k | Status VExprContext::execute(const Block* block, ColumnWithTypeAndName& result_data) { |
99 | 42.7k | Status st; |
100 | 42.7k | ColumnPtr result_column; |
101 | 42.7k | RETURN_IF_CATCH_EXCEPTION( |
102 | 42.7k | { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); }); |
103 | 42.7k | RETURN_IF_ERROR(st); |
104 | 42.7k | result_data.column = result_column; |
105 | 42.7k | result_data.type = execute_type(block); |
106 | 42.7k | result_data.name = _root->expr_name(); |
107 | 42.7k | return Status::OK(); |
108 | 42.7k | } |
109 | | |
110 | 1.26M | DataTypePtr VExprContext::execute_type(const Block* block) { |
111 | 1.26M | return _root->execute_type(block); |
112 | 1.26M | } |
113 | | |
114 | 1.12M | Status VExprContext::execute_const_expr(ColumnWithTypeAndName& result) { |
115 | 1.12M | Status st; |
116 | 1.12M | RETURN_IF_CATCH_EXCEPTION( |
117 | 1.12M | { st = _root->execute_column(this, nullptr, nullptr, 1, result.column); }); |
118 | 1.12M | RETURN_IF_ERROR(st); |
119 | 1.12M | result.type = _root->execute_type(nullptr); |
120 | 1.12M | result.name = _root->expr_name(); |
121 | 1.12M | return Status::OK(); |
122 | 1.12M | } |
123 | | |
124 | 1.23M | [[nodiscard]] const std::string& VExprContext::expr_name() const { |
125 | 1.23M | return _root->expr_name(); |
126 | 1.23M | } |
127 | | |
128 | 0 | bool VExprContext::is_blockable() const { |
129 | 0 | return _root->is_blockable(); |
130 | 0 | } |
131 | | |
132 | 8.10M | Status VExprContext::prepare(RuntimeState* state, const RowDescriptor& row_desc) { |
133 | 8.10M | _prepared = true; |
134 | 8.10M | Status st; |
135 | 8.10M | RETURN_IF_CATCH_EXCEPTION({ st = _root->prepare(state, row_desc, this); }); |
136 | 8.10M | return st; |
137 | 8.10M | } |
138 | | |
139 | 8.10M | Status VExprContext::open(RuntimeState* state) { |
140 | 8.10M | DCHECK(_prepared); |
141 | 8.10M | if (_opened) { |
142 | 4.52k | return Status::OK(); |
143 | 4.52k | } |
144 | 8.10M | _opened = true; |
145 | | // Fragment-local state is only initialized for original contexts. Clones inherit the |
146 | | // original's fragment state and only need to have thread-local state initialized. |
147 | 8.10M | FunctionContext::FunctionStateScope scope = |
148 | 8.10M | _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL; |
149 | 8.10M | Status st; |
150 | 8.10M | RETURN_IF_CATCH_EXCEPTION({ st = _root->open(state, this, scope); }); |
151 | 8.10M | return st; |
152 | 8.10M | } |
153 | | |
154 | 30.5M | void VExprContext::close() { |
155 | | // Sometimes expr context may not have a root, then it need not call close |
156 | 30.5M | if (_root == nullptr) { |
157 | 0 | return; |
158 | 0 | } |
159 | 30.5M | FunctionContext::FunctionStateScope scope = |
160 | 30.5M | _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL; |
161 | 30.5M | _root->close(this, scope); |
162 | 30.5M | } |
163 | | |
164 | 22.2M | Status VExprContext::clone(RuntimeState* state, VExprContextSPtr& new_ctx) { |
165 | 18.4E | DCHECK(_prepared) << "expr context not prepared"; |
166 | 22.2M | DCHECK(_opened); |
167 | 22.2M | DCHECK(new_ctx.get() == nullptr); |
168 | | |
169 | 22.2M | new_ctx = std::make_shared<VExprContext>(_root); |
170 | 22.2M | for (auto& _fn_context : _fn_contexts) { |
171 | 1.64M | new_ctx->_fn_contexts.push_back(_fn_context->clone()); |
172 | 1.64M | } |
173 | | |
174 | 22.2M | new_ctx->_is_clone = true; |
175 | 22.2M | new_ctx->_prepared = true; |
176 | 22.2M | new_ctx->_opened = true; |
177 | | // segment_v2::AnnRangeSearchRuntime should be cloned as well. |
178 | | // The object of segment_v2::AnnRangeSearchRuntime is not shared by threads. |
179 | 22.2M | new_ctx->_ann_range_search_runtime = this->_ann_range_search_runtime; |
180 | | |
181 | 22.2M | return _root->open(state, new_ctx.get(), FunctionContext::THREAD_LOCAL); |
182 | 22.2M | } |
183 | | |
184 | 0 | void VExprContext::clone_fn_contexts(VExprContext* other) { |
185 | 0 | for (auto& _fn_context : _fn_contexts) { |
186 | 0 | other->_fn_contexts.push_back(_fn_context->clone()); |
187 | 0 | } |
188 | 0 | } |
189 | | |
190 | | int VExprContext::register_function_context(RuntimeState* state, const DataTypePtr& return_type, |
191 | 1.03M | const std::vector<DataTypePtr>& arg_types) { |
192 | 1.03M | _fn_contexts.push_back(FunctionContext::create_context(state, return_type, arg_types)); |
193 | 1.03M | _fn_contexts.back()->set_check_overflow_for_decimal(state->check_overflow_for_decimal()); |
194 | 1.03M | _fn_contexts.back()->set_enable_strict_mode(state->enable_strict_mode()); |
195 | 1.03M | return static_cast<int>(_fn_contexts.size()) - 1; |
196 | 1.03M | } |
197 | | |
198 | 19.7k | Status VExprContext::evaluate_inverted_index(uint32_t segment_num_rows) { |
199 | 19.7k | Status st; |
200 | 19.7k | RETURN_IF_CATCH_EXCEPTION({ st = _root->evaluate_inverted_index(this, segment_num_rows); }); |
201 | 19.6k | return st; |
202 | 19.7k | } |
203 | | |
204 | | ZoneMapFilterResult VExprContext::evaluate_zonemap_filter(const VExprContextSPtrs& conjuncts, |
205 | 49.6k | const ZoneMapEvalContext& ctx) { |
206 | 65.1k | for (const auto& conjunct : conjuncts) { |
207 | 65.1k | DORIS_CHECK(conjunct != nullptr); |
208 | 65.1k | const auto& root = conjunct->root(); |
209 | 65.1k | DORIS_CHECK(root != nullptr); |
210 | 65.1k | if (!root->can_evaluate_zonemap_filter()) { |
211 | 20.8k | continue; |
212 | 20.8k | } |
213 | 44.3k | if (root->evaluate_zonemap_filter(ctx) == ZoneMapFilterResult::kNoMatch) { |
214 | 13.8k | return ZoneMapFilterResult::kNoMatch; |
215 | 13.8k | } |
216 | 44.3k | } |
217 | 35.8k | return ZoneMapFilterResult::kMayMatch; |
218 | 49.6k | } |
219 | | |
220 | | ZoneMapFilterResult VExprContext::evaluate_dictionary_filter(const VExprContextSPtrs& conjuncts, |
221 | 211k | const DictionaryEvalContext& ctx) { |
222 | 212k | for (const auto& conjunct : conjuncts) { |
223 | 212k | DORIS_CHECK(conjunct != nullptr); |
224 | 212k | const auto& root = conjunct->root(); |
225 | 212k | DORIS_CHECK(root != nullptr); |
226 | 212k | if (!root->can_evaluate_dictionary_filter()) { |
227 | 0 | continue; |
228 | 0 | } |
229 | 212k | if (root->evaluate_dictionary_filter(ctx) == ZoneMapFilterResult::kNoMatch) { |
230 | 62.6k | return ZoneMapFilterResult::kNoMatch; |
231 | 62.6k | } |
232 | 212k | } |
233 | 148k | return ZoneMapFilterResult::kMayMatch; |
234 | 211k | } |
235 | | |
236 | | ZoneMapFilterResult VExprContext::evaluate_bloom_filter(const VExprContextSPtrs& conjuncts, |
237 | 13 | const BloomFilterEvalContext& ctx) { |
238 | 13 | for (const auto& conjunct : conjuncts) { |
239 | 13 | DORIS_CHECK(conjunct != nullptr); |
240 | 13 | const auto& root = conjunct->root(); |
241 | 13 | DORIS_CHECK(root != nullptr); |
242 | 13 | if (!root->can_evaluate_bloom_filter()) { |
243 | 0 | continue; |
244 | 0 | } |
245 | 13 | if (root->evaluate_bloom_filter(ctx) == ZoneMapFilterResult::kNoMatch) { |
246 | 1 | return ZoneMapFilterResult::kNoMatch; |
247 | 1 | } |
248 | 13 | } |
249 | 12 | return ZoneMapFilterResult::kMayMatch; |
250 | 13 | } |
251 | | |
252 | 19.3k | bool VExprContext::all_expr_inverted_index_evaluated() { |
253 | 19.3k | return _index_context->has_index_result_for_expr(_root.get()); |
254 | 19.3k | } |
255 | | |
256 | 52 | Status VExprContext::filter_block(VExprContext* vexpr_ctx, Block* block) { |
257 | 52 | if (vexpr_ctx == nullptr || block->rows() == 0) { |
258 | 0 | return Status::OK(); |
259 | 0 | } |
260 | 52 | ColumnPtr filter_column; |
261 | 52 | RETURN_IF_ERROR(vexpr_ctx->execute(block, filter_column)); |
262 | 52 | size_t filter_column_id = block->columns(); |
263 | 52 | block->insert({filter_column, vexpr_ctx->execute_type(block), "filter_column"}); |
264 | 52 | vexpr_ctx->_memory_usage = filter_column->allocated_bytes(); |
265 | 52 | return Block::filter_block(block, filter_column_id, filter_column_id); |
266 | 52 | } |
267 | | |
268 | | Status VExprContext::filter_block(const VExprContextSPtrs& expr_contexts, Block* block, |
269 | 1.86M | size_t column_to_keep) { |
270 | 1.86M | if (expr_contexts.empty() || block->rows() == 0) { |
271 | 1.75M | return Status::OK(); |
272 | 1.75M | } |
273 | | |
274 | 111k | ColumnNumbers columns_to_filter(column_to_keep); |
275 | 111k | std::iota(columns_to_filter.begin(), columns_to_filter.end(), 0); |
276 | | |
277 | 111k | return execute_conjuncts_and_filter_block(expr_contexts, block, columns_to_filter, |
278 | 111k | static_cast<int>(column_to_keep)); |
279 | 1.86M | } |
280 | | |
281 | | Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs, |
282 | | const std::vector<IColumn::Filter*>* filters, Block* block, |
283 | 8.26k | IColumn::Filter* result_filter, bool* can_filter_all) { |
284 | 8.26k | return execute_conjuncts(ctxs, filters, false, block, result_filter, can_filter_all); |
285 | 8.26k | } |
286 | | |
287 | | Status VExprContext::execute_filter(const Block* block, uint8_t* __restrict result_filter_data, |
288 | 486k | size_t rows, bool accept_null, bool* can_filter_all) { |
289 | 486k | return _root->execute_filter(this, block, result_filter_data, rows, accept_null, |
290 | 486k | can_filter_all); |
291 | 486k | } |
292 | | |
293 | | Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs, |
294 | | const std::vector<IColumn::Filter*>* filters, |
295 | | bool accept_null, const Block* block, |
296 | 454k | IColumn::Filter* result_filter, bool* can_filter_all) { |
297 | 454k | size_t rows = block->rows(); |
298 | 454k | DCHECK_EQ(result_filter->size(), rows); |
299 | 454k | *can_filter_all = false; |
300 | 454k | auto* __restrict result_filter_data = result_filter->data(); |
301 | 454k | for (const auto& ctx : ctxs) { |
302 | 350k | RETURN_IF_ERROR( |
303 | 350k | ctx->execute_filter(block, result_filter_data, rows, accept_null, can_filter_all)); |
304 | 350k | if (*can_filter_all) { |
305 | 69.2k | return Status::OK(); |
306 | 69.2k | } |
307 | 350k | } |
308 | 384k | if (filters != nullptr) { |
309 | 268 | for (auto* filter : *filters) { |
310 | 13 | auto* __restrict filter_data = filter->data(); |
311 | 13 | const size_t size = filter->size(); |
312 | 141 | for (size_t i = 0; i < size; ++i) { |
313 | 128 | result_filter_data[i] &= filter_data[i]; |
314 | 128 | } |
315 | 13 | if (memchr(result_filter_data, 0x1, size) == nullptr) { |
316 | 0 | *can_filter_all = true; |
317 | 0 | return Status::OK(); |
318 | 0 | } |
319 | 13 | } |
320 | 268 | } |
321 | 384k | return Status::OK(); |
322 | 384k | } |
323 | | |
324 | | Status VExprContext::execute_conjuncts_selective(const VExprContextSPtrs& ctxs, |
325 | | const std::vector<IColumn::Filter*>* filters, |
326 | | const Block* block, IColumn::Filter* result_filter, |
327 | 507 | bool* can_filter_all) { |
328 | 507 | size_t rows = block->rows(); |
329 | 507 | DCHECK_EQ(result_filter->size(), rows); |
330 | 507 | *can_filter_all = false; |
331 | 507 | auto* __restrict result_filter_data = result_filter->data(); |
332 | | |
333 | | // Fold any pre-existing masks (delete / position-delete filters) into result_filter first, |
334 | | // so the surviving set starts from rows those masks already keep. |
335 | 507 | size_t surviving = rows; |
336 | 507 | if (filters != nullptr) { |
337 | 1 | for (auto* filter : *filters) { |
338 | 1 | const auto* __restrict fdata = filter->data(); |
339 | 101 | for (size_t i = 0; i < rows; ++i) { |
340 | 100 | result_filter_data[i] &= fdata[i]; |
341 | 100 | } |
342 | 1 | } |
343 | 1 | surviving = rows - |
344 | 1 | simd::count_zero_num(reinterpret_cast<const int8_t*>(result_filter_data), rows); |
345 | 1 | if (surviving == 0) { |
346 | 0 | *can_filter_all = true; |
347 | 0 | return Status::OK(); |
348 | 0 | } |
349 | 1 | } |
350 | | |
351 | | // Below this surviving fraction, gathering the surviving rows for a conjunct's inputs is |
352 | | // worth its memcpy cost; above it, evaluate the conjunct full-width (like the original |
353 | | // execute_conjuncts) so we do not gather nearly the whole block. Mirrors PrestoDB selecting |
354 | | // only once a batch has meaningfully shrunk. |
355 | 507 | constexpr double kSelectiveGatherThreshold = 0.5; |
356 | | |
357 | | // `selection` holds the original row indices still alive. It is (re)built from |
358 | | // result_filter lazily, only when a conjunct is about to be evaluated selectively. |
359 | 507 | IColumn::Selector selection; |
360 | 507 | bool selection_valid = false; |
361 | | |
362 | 507 | auto rebuild_selection = [&]() { |
363 | 314 | selection.clear(); |
364 | 314 | selection.reserve(surviving); |
365 | 63.9k | for (size_t i = 0; i < rows; ++i) { |
366 | 63.6k | if (result_filter_data[i]) { |
367 | 13.4k | selection.push_back(static_cast<IColumn::Selector::value_type>(i)); |
368 | 13.4k | } |
369 | 63.6k | } |
370 | 314 | selection_valid = true; |
371 | 314 | }; |
372 | | |
373 | 1.40k | for (const auto& ctx : ctxs) { |
374 | 1.40k | if (ctx == nullptr) { |
375 | 0 | continue; |
376 | 0 | } |
377 | | // Runtime-filter wrappers carry selectivity tracking and counter side effects in their |
378 | | // execute_filter override, so they must run full-width; they are also cheap (bloom / |
379 | | // min-max) and belong up front. A high surviving fraction also stays on the full-width |
380 | | // path, where gathering would copy almost the whole block for no benefit. |
381 | 1.40k | const bool use_selective = !ctx->root()->is_rf_wrapper() && |
382 | 1.40k | surviving < static_cast<size_t>(static_cast<double>(rows) * |
383 | 1.09k | kSelectiveGatherThreshold); |
384 | 1.40k | if (!use_selective) { |
385 | | // Full-width path: input is every row still alive (result_filter carries them). |
386 | 860 | const size_t input_rows = surviving; |
387 | | // Sample every kTimingSampleEvery-th batch. RF wrappers are skipped: their |
388 | | // execute_filter includes their own selectivity/counter side effects and |
389 | | // wrapping it in another clock read is noise. The static cost stays as the |
390 | | // cold-start estimate; timed rows accumulate on the non-RF conjuncts we care |
391 | | // about reordering. |
392 | 860 | const bool sample = |
393 | 860 | !ctx->root()->is_rf_wrapper() && ctx->filter_runtime_stats().should_sample(); |
394 | 860 | const int64_t t0 = sample ? MonotonicNanos() : 0; |
395 | 860 | RETURN_IF_ERROR( |
396 | 860 | ctx->execute_filter(block, result_filter_data, rows, false, can_filter_all)); |
397 | 860 | const int64_t elapsed_ns = sample ? MonotonicNanos() - t0 : 0; |
398 | 860 | if (*can_filter_all) { |
399 | 27 | ctx->filter_runtime_stats().update(static_cast<int64_t>(input_rows), 0, elapsed_ns); |
400 | 27 | return Status::OK(); |
401 | 27 | } |
402 | 833 | surviving = rows - simd::count_zero_num( |
403 | 833 | reinterpret_cast<const int8_t*>(result_filter_data), rows); |
404 | 833 | ctx->filter_runtime_stats().update(static_cast<int64_t>(input_rows), |
405 | 833 | static_cast<int64_t>(surviving), elapsed_ns); |
406 | 833 | if (surviving == 0) { |
407 | 0 | *can_filter_all = true; |
408 | 0 | return Status::OK(); |
409 | 0 | } |
410 | 833 | selection_valid = false; |
411 | 833 | continue; |
412 | 833 | } |
413 | | |
414 | 549 | if (!selection_valid) { |
415 | 314 | rebuild_selection(); |
416 | 314 | } |
417 | | // Evaluate this conjunct only on the surviving rows. execute_column with a selector |
418 | | // gathers the inputs down to `selection.size()` rows, so a heavy function runs once |
419 | | // per surviving row rather than once per block row. |
420 | 549 | const size_t count = selection.size(); |
421 | 549 | ColumnPtr result_column; |
422 | 549 | const bool sample = ctx->filter_runtime_stats().should_sample(); |
423 | 549 | const int64_t t0 = sample ? MonotonicNanos() : 0; |
424 | 549 | RETURN_IF_ERROR( |
425 | 549 | ctx->root()->execute_column(ctx.get(), block, &selection, count, result_column)); |
426 | 549 | const int64_t elapsed_ns = sample ? MonotonicNanos() - t0 : 0; |
427 | 549 | auto [filter_column, is_const] = unpack_if_const(result_column); |
428 | | |
429 | 549 | if (is_const) { |
430 | | // Const predicate over the surviving rows: keep all or drop all of them. |
431 | 0 | const bool keep = !filter_column->is_null_at(0) && filter_column->get_bool(0); |
432 | 0 | ctx->filter_runtime_stats().update(static_cast<int64_t>(count), |
433 | 0 | keep ? static_cast<int64_t>(count) : 0, elapsed_ns); |
434 | 0 | if (!keep) { |
435 | 0 | memset(result_filter_data, 0, rows); |
436 | 0 | *can_filter_all = true; |
437 | 0 | return Status::OK(); |
438 | 0 | } |
439 | | // keep == true: result_filter and selection unchanged. |
440 | 0 | continue; |
441 | 0 | } |
442 | | |
443 | | // Narrow the surviving set: keep selection[j] only where the predicate is true and not |
444 | | // NULL at position j (accept_null == false, matching execute_filter's scan semantics). |
445 | 549 | IColumn::Selector next; |
446 | 549 | next.reserve(count); |
447 | 549 | if (const auto* nullable = check_and_get_column<ColumnNullable>(*filter_column)) { |
448 | 549 | const auto* __restrict fdata = |
449 | 549 | assert_cast<const ColumnUInt8&>(nullable->get_nested_column()) |
450 | 549 | .get_data() |
451 | 549 | .data(); |
452 | 549 | const auto* __restrict nmap = nullable->get_null_map_data().data(); |
453 | 18.1k | for (size_t j = 0; j < count; ++j) { |
454 | 17.6k | if (!nmap[j] && fdata[j]) { |
455 | 7.69k | next.push_back(selection[j]); |
456 | 9.95k | } else { |
457 | 9.95k | result_filter_data[selection[j]] = 0; |
458 | 9.95k | } |
459 | 17.6k | } |
460 | 549 | } else { |
461 | 0 | const auto* __restrict fdata = |
462 | 0 | assert_cast<const ColumnUInt8&>(*filter_column).get_data().data(); |
463 | 0 | for (size_t j = 0; j < count; ++j) { |
464 | 0 | if (fdata[j]) { |
465 | 0 | next.push_back(selection[j]); |
466 | 0 | } else { |
467 | 0 | result_filter_data[selection[j]] = 0; |
468 | 0 | } |
469 | 0 | } |
470 | 0 | } |
471 | 549 | selection.swap(next); |
472 | 549 | ctx->filter_runtime_stats().update(static_cast<int64_t>(count), |
473 | 549 | static_cast<int64_t>(selection.size()), elapsed_ns); |
474 | 549 | surviving = selection.size(); |
475 | 549 | selection_valid = true; |
476 | 549 | if (surviving == 0) { |
477 | 73 | *can_filter_all = true; |
478 | 73 | return Status::OK(); |
479 | 73 | } |
480 | 549 | } |
481 | 407 | return Status::OK(); |
482 | 507 | } |
483 | | |
484 | | bool VExprContext::adaptive_reorder_conjuncts(VExprContextSPtrs& conjuncts, int64_t min_rows, |
485 | 9 | double min_cost) { |
486 | 9 | if (conjuncts.size() < 2) { |
487 | 0 | return false; |
488 | 0 | } |
489 | | // Adaptive reorder only pays off when some conjunct is expensive: shuffling cheap-only |
490 | | // predicates saves less than the reorder itself costs. "Expensive" is either |
491 | | // (a) the static structural estimate scored high (cost >= min_cost), or |
492 | | // (b) the measured per-row cost scored high (per_row_ns >= min_per_row_ns). |
493 | | // Case (b) catches two failure modes of the static score: a FUNCTION_CALL underestimate |
494 | | // (length(col) is nowhere near 100ns/row) and inability to distinguish two calls that |
495 | | // score the same but run 10-100x apart. Also gate on every measurable conjunct having |
496 | | // seen enough rows so an early noisy selectivity does not churn the order. RF wrappers |
497 | | // run full-width and stay in front, so they are exempt from both checks. |
498 | 9 | constexpr double kMinPerRowNs = kAdaptiveReorderMinPerRowNs; |
499 | 9 | bool has_expensive = false; |
500 | 17 | for (const auto& ctx : conjuncts) { |
501 | 17 | if (ctx == nullptr || ctx->root()->is_rf_wrapper()) { |
502 | 1 | continue; |
503 | 1 | } |
504 | 16 | const auto& stats = ctx->filter_runtime_stats(); |
505 | 16 | if (stats.input_rows < min_rows) { |
506 | 1 | return false; |
507 | 1 | } |
508 | 15 | if (VExpr::compute_conjunct_cost(ctx->root()) >= min_cost || |
509 | 15 | stats.per_row_ns() >= kMinPerRowNs) { |
510 | 10 | has_expensive = true; |
511 | 10 | } |
512 | 15 | } |
513 | 8 | if (!has_expensive) { |
514 | 1 | return false; |
515 | 1 | } |
516 | | // Sort key: per-row cost divided by measured drop fraction -- cheap predicates that |
517 | | // eliminate many rows sort first, an expensive predicate that turns out unselective sinks. |
518 | | // Cost prefers the measured per_row_ns once enough sampled rows have accrued, and falls |
519 | | // back on the static structural estimate otherwise. Selectivity stays the (free) |
520 | | // measurement. eps floors the divisor so a conjunct that drops nothing sorts last instead |
521 | | // of dividing by zero. RF wrappers score 0 to stay in front. The two cost sources are on |
522 | | // different units (ns vs structural score) but this only affects the absolute magnitude |
523 | | // of the key -- ordering is preserved because either every conjunct we care about has a |
524 | | // measurement (comparable among themselves) or none does (all fall back to structural), |
525 | | // and RF wrappers pin at 0 either way. |
526 | 7 | constexpr double kEps = 1e-6; |
527 | 14 | auto sort_key = [kEps](const VExprContextSPtr& c) -> double { |
528 | 14 | if (c == nullptr || c->root()->is_rf_wrapper()) { |
529 | 1 | return 0.0; |
530 | 1 | } |
531 | 13 | const auto& stats = c->filter_runtime_stats(); |
532 | 13 | const double per_row = stats.per_row_ns(); |
533 | 13 | const double cost = per_row > 0.0 ? per_row : VExpr::compute_conjunct_cost(c->root()); |
534 | 13 | return cost / std::max(stats.dropped_fraction(), kEps); |
535 | 14 | }; |
536 | 7 | std::stable_sort(conjuncts.begin(), conjuncts.end(), |
537 | 7 | [&sort_key](const VExprContextSPtr& a, const VExprContextSPtr& b) { |
538 | 7 | return sort_key(a) < sort_key(b); |
539 | 7 | }); |
540 | 7 | return true; |
541 | 8 | } |
542 | | |
543 | | Status VExprContext::execute_conjuncts(const VExprContextSPtrs& conjuncts, const Block* block, |
544 | 371 | ColumnUInt8& null_map, IColumn::Filter& filter) { |
545 | 371 | const auto& rows = block->rows(); |
546 | 371 | if (rows == 0) { |
547 | 0 | return Status::OK(); |
548 | 0 | } |
549 | 371 | if (null_map.size() != rows) { |
550 | 0 | return Status::InternalError("null_map.size()!=rows, null_map.size()={}, rows={}", |
551 | 0 | null_map.size(), rows); |
552 | 0 | } |
553 | | |
554 | 371 | auto* final_null_map = null_map.get_data().data(); |
555 | 371 | auto* final_filter_ptr = filter.data(); |
556 | | |
557 | 371 | for (const auto& conjunct : conjuncts) { |
558 | 70 | ColumnPtr result_column; |
559 | 70 | RETURN_IF_ERROR(conjunct->execute(block, result_column)); |
560 | 70 | auto [filter_column, is_const] = unpack_if_const(result_column); |
561 | 70 | const auto* nullable_column = assert_cast<const ColumnNullable*>(filter_column.get()); |
562 | 70 | if (!is_const) { |
563 | 54 | const ColumnPtr& nested_column = nullable_column->get_nested_column_ptr(); |
564 | 54 | const IColumn::Filter& result = |
565 | 54 | assert_cast<const ColumnUInt8&>(*nested_column).get_data(); |
566 | 54 | const auto* __restrict filter_data = result.data(); |
567 | 54 | const auto* __restrict null_map_data = nullable_column->get_null_map_data().data(); |
568 | 54 | DCHECK_EQ(rows, nullable_column->size()); |
569 | | |
570 | 737 | for (size_t i = 0; i != rows; ++i) { |
571 | | // null and null => null |
572 | | // null and true => null |
573 | | // null and false => false |
574 | 683 | final_null_map[i] = (final_null_map[i] & (null_map_data[i] | filter_data[i])) | |
575 | 683 | (null_map_data[i] & (final_null_map[i] | final_filter_ptr[i])); |
576 | 683 | final_filter_ptr[i] = final_filter_ptr[i] & filter_data[i]; |
577 | 683 | } |
578 | 54 | } else { |
579 | 16 | bool filter_data = nullable_column->get_bool(0); |
580 | 16 | bool null_map_data = nullable_column->is_null_at(0); |
581 | 108 | for (size_t i = 0; i != rows; ++i) { |
582 | | // null and null => null |
583 | | // null and true => null |
584 | | // null and false => false |
585 | 92 | final_null_map[i] = (final_null_map[i] & (null_map_data | filter_data)) | |
586 | 92 | (null_map_data & (final_null_map[i] | final_filter_ptr[i])); |
587 | 92 | final_filter_ptr[i] = final_filter_ptr[i] & filter_data; |
588 | 92 | } |
589 | 16 | } |
590 | 70 | } |
591 | 371 | return Status::OK(); |
592 | 371 | } |
593 | | |
594 | | // TODO Performance Optimization |
595 | | // need exception safety |
596 | | Status VExprContext::execute_conjuncts_and_filter_block(const VExprContextSPtrs& ctxs, Block* block, |
597 | | std::vector<uint32_t>& columns_to_filter, |
598 | 113k | int column_to_keep) { |
599 | 113k | IColumn::Filter result_filter(block->rows(), 1); |
600 | 113k | bool can_filter_all; |
601 | | |
602 | 113k | _reset_memory_usage(ctxs); |
603 | | |
604 | 113k | RETURN_IF_ERROR( |
605 | 113k | execute_conjuncts(ctxs, nullptr, false, block, &result_filter, &can_filter_all)); |
606 | | |
607 | | // Accumulate the usage of `result_filter` into the first context. |
608 | 113k | if (!ctxs.empty()) { |
609 | 113k | ctxs[0]->_memory_usage += result_filter.allocated_bytes(); |
610 | 113k | } |
611 | 113k | if (can_filter_all) { |
612 | 59.5k | for (auto& col : columns_to_filter) { |
613 | 59.5k | auto& column = block->get_by_position(col).column; |
614 | 59.5k | if (column->is_exclusive()) { |
615 | 51.4k | column->assert_mutable()->clear(); |
616 | 51.4k | } else { |
617 | 8.07k | column = column->clone_empty(); |
618 | 8.07k | } |
619 | 59.5k | } |
620 | 98.1k | } else { |
621 | 98.1k | try { |
622 | 98.1k | Block::filter_block_internal(block, columns_to_filter, result_filter); |
623 | 98.1k | } catch (const Exception& e) { |
624 | 0 | std::string str; |
625 | 0 | for (auto ctx : ctxs) { |
626 | 0 | if (str.length()) { |
627 | 0 | str += ","; |
628 | 0 | } |
629 | 0 | str += ctx->root()->debug_string(); |
630 | 0 | } |
631 | |
|
632 | 0 | return Status::InternalError( |
633 | 0 | "filter_block_internal meet exception, exprs=[{}], exception={}", str, |
634 | 0 | e.what()); |
635 | 0 | } |
636 | 98.1k | } |
637 | 113k | Block::erase_useless_column(block, column_to_keep); |
638 | 113k | return Status::OK(); |
639 | 113k | } |
640 | | |
641 | | Status VExprContext::execute_conjuncts_and_filter_block(const VExprContextSPtrs& ctxs, Block* block, |
642 | | std::vector<uint32_t>& columns_to_filter, |
643 | | int column_to_keep, |
644 | 131 | IColumn::Filter& filter) { |
645 | 131 | _reset_memory_usage(ctxs); |
646 | 131 | filter.resize_fill(block->rows(), 1); |
647 | 131 | bool can_filter_all; |
648 | 131 | RETURN_IF_ERROR(execute_conjuncts(ctxs, nullptr, false, block, &filter, &can_filter_all)); |
649 | | |
650 | | // Accumulate the usage of `result_filter` into the first context. |
651 | 131 | if (!ctxs.empty()) { |
652 | 107 | ctxs[0]->_memory_usage += filter.allocated_bytes(); |
653 | 107 | } |
654 | 131 | if (can_filter_all) { |
655 | 106 | for (auto& col : columns_to_filter) { |
656 | 106 | auto& column = block->get_by_position(col).column; |
657 | 106 | if (column->is_exclusive()) { |
658 | 106 | column->assert_mutable()->clear(); |
659 | 106 | } else { |
660 | 0 | column = column->clone_empty(); |
661 | 0 | } |
662 | 106 | } |
663 | 100 | } else { |
664 | 100 | RETURN_IF_CATCH_EXCEPTION(Block::filter_block_internal(block, columns_to_filter, filter)); |
665 | 100 | } |
666 | | |
667 | 131 | Block::erase_useless_column(block, column_to_keep); |
668 | 131 | return Status::OK(); |
669 | 131 | } |
670 | | |
671 | | // do_projection: for some query(e.g. in MultiCastDataStreamerSourceOperator::get_block()), |
672 | | // output_vexpr_ctxs will output the same column more than once, and if the output_block |
673 | | // is mem-reused later, it will trigger DCHECK_EQ(d.column->use_count(), 1) failure when |
674 | | // doing Block::clear_column_data, set do_projection to true to copy the column data to |
675 | | // avoid this problem. |
676 | | Status VExprContext::get_output_block_after_execute_exprs( |
677 | | const VExprContextSPtrs& output_vexpr_ctxs, const Block& input_block, Block* output_block, |
678 | 250k | bool do_projection) { |
679 | 250k | auto rows = input_block.rows(); |
680 | 250k | ColumnsWithTypeAndName result_columns; |
681 | 250k | _reset_memory_usage(output_vexpr_ctxs); |
682 | | |
683 | 1.20M | for (const auto& vexpr_ctx : output_vexpr_ctxs) { |
684 | 1.20M | ColumnPtr result_column; |
685 | 1.20M | RETURN_IF_ERROR(vexpr_ctx->execute(&input_block, result_column)); |
686 | | |
687 | 1.20M | auto type = vexpr_ctx->execute_type(&input_block); |
688 | 1.20M | const auto& name = vexpr_ctx->expr_name(); |
689 | | |
690 | 1.20M | vexpr_ctx->_memory_usage += result_column->allocated_bytes(); |
691 | 1.20M | if (do_projection) { |
692 | 35.1k | result_columns.emplace_back(result_column->clone_resized(rows), type, name); |
693 | | |
694 | 1.17M | } else { |
695 | 1.17M | result_columns.emplace_back(result_column, type, name); |
696 | 1.17M | } |
697 | 1.20M | } |
698 | 250k | *output_block = {result_columns}; |
699 | 250k | return Status::OK(); |
700 | 250k | } |
701 | | |
702 | 364k | void VExprContext::_reset_memory_usage(const VExprContextSPtrs& contexts) { |
703 | 364k | std::for_each(contexts.begin(), contexts.end(), |
704 | 1.39M | [](auto&& context) { context->_memory_usage = 0; }); |
705 | 364k | } |
706 | | |
707 | 21.6k | void VExprContext::prepare_ann_range_search(const doris::VectorSearchUserParams& params) { |
708 | 21.6k | if (_root == nullptr) { |
709 | 0 | return; |
710 | 0 | } |
711 | | |
712 | 21.6k | _root->prepare_ann_range_search(params, _ann_range_search_runtime, _suitable_for_ann_index); |
713 | 18.4E | VLOG_DEBUG << fmt::format("Prepare ann range search result {}, _suitable_for_ann_index {}", |
714 | 18.4E | this->_ann_range_search_runtime.to_string(), |
715 | 18.4E | this->_suitable_for_ann_index); |
716 | 21.6k | return; |
717 | 21.6k | } |
718 | | |
719 | | Status VExprContext::evaluate_ann_range_search( |
720 | | const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& cid_to_index_iterators, |
721 | | const std::vector<ColumnId>& idx_to_cid, |
722 | | const std::vector<std::unique_ptr<segment_v2::ColumnIterator>>& column_iterators, |
723 | | const std::unordered_map<VExprContext*, std::unordered_map<ColumnId, VExpr*>>& |
724 | | common_expr_to_slotref_map, |
725 | | size_t rows_of_segment, roaring::Roaring& row_bitmap, |
726 | | segment_v2::AnnIndexStats& ann_index_stats, bool enable_result_cache, |
727 | 19.4k | bool* ann_range_search_executed) { |
728 | 19.4k | if (ann_range_search_executed != nullptr) { |
729 | 19.4k | *ann_range_search_executed = false; |
730 | 19.4k | } |
731 | 19.4k | if (_root == nullptr) { |
732 | 0 | return Status::OK(); |
733 | 0 | } |
734 | | |
735 | 19.4k | AnnRangeSearchEvaluationResult evaluation_result; |
736 | 19.4k | RETURN_IF_ERROR(_root->evaluate_ann_range_search( |
737 | 19.4k | _ann_range_search_runtime, cid_to_index_iterators, idx_to_cid, column_iterators, |
738 | 19.4k | rows_of_segment, row_bitmap, ann_index_stats, enable_result_cache, evaluation_result)); |
739 | | |
740 | 19.4k | if (!evaluation_result.executed) { |
741 | 19.3k | return Status::OK(); |
742 | 19.3k | } |
743 | 57 | if (ann_range_search_executed != nullptr) { |
744 | 28 | *ann_range_search_executed = true; |
745 | 28 | } |
746 | | |
747 | 57 | DCHECK(_index_context != nullptr); |
748 | 57 | _index_context->set_index_result_for_expr( |
749 | 57 | _root.get(), |
750 | 57 | segment_v2::InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(row_bitmap), |
751 | 57 | std::make_shared<roaring::Roaring>())); |
752 | | |
753 | 57 | if (!evaluation_result.dist_fulfilled) { |
754 | | // Do not perform index scan in this case. |
755 | 2 | return Status::OK(); |
756 | 2 | } |
757 | | |
758 | 57 | DCHECK_LT(_ann_range_search_runtime.src_col_idx, idx_to_cid.size()); |
759 | 55 | const auto src_col_idx = cast_set<int>(_ann_range_search_runtime.src_col_idx); |
760 | 55 | const auto src_col_key = cast_set<ColumnId>(_ann_range_search_runtime.src_col_idx); |
761 | 55 | auto slot_ref_map_it = common_expr_to_slotref_map.find(this); |
762 | 55 | if (slot_ref_map_it == common_expr_to_slotref_map.end()) { |
763 | 1 | return Status::OK(); |
764 | 1 | } |
765 | 54 | auto& slot_ref_map = slot_ref_map_it->second; |
766 | 54 | auto slot_ref_it = slot_ref_map.find(src_col_key); |
767 | 54 | if (slot_ref_it == slot_ref_map.end()) { |
768 | 0 | return Status::OK(); |
769 | 0 | } |
770 | 54 | const VExpr* slot_ref_expr_addr = slot_ref_it->second; |
771 | 54 | _index_context->set_true_for_index_status(slot_ref_expr_addr, src_col_idx); |
772 | | |
773 | 54 | VLOG_DEBUG << fmt::format( |
774 | 29 | "Evaluate ann range search for expr {}, src_col_idx {}, cid {}, row_bitmap " |
775 | 29 | "cardinality {}", |
776 | 29 | _root->debug_string(), src_col_idx, idx_to_cid[_ann_range_search_runtime.src_col_idx], |
777 | 29 | row_bitmap.cardinality()); |
778 | 54 | return Status::OK(); |
779 | 54 | } |
780 | | |
781 | 593k | uint64_t VExprContext::get_digest(uint64_t seed) const { |
782 | 593k | return _root->get_digest(seed); |
783 | 593k | } |
784 | | |
785 | 1.30M | double VExprContext::execute_cost() const { |
786 | 1.30M | if (_root == nullptr) { |
787 | | // When there is no expression root, treat the cost as a base value. |
788 | | // This avoids null dereferences while keeping a deterministic cost. |
789 | 0 | return 0.0; |
790 | 0 | } |
791 | 1.30M | return _root->execute_cost(); |
792 | 1.30M | } |
793 | | |
794 | | } // namespace doris |