Coverage Report

Created: 2026-03-13 09:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/vexpr_context.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/vexpr_context.h"
19
20
#include <algorithm>
21
#include <cstdint>
22
#include <string>
23
24
#include "common/compiler_util.h" // IWYU pragma: keep
25
#include "common/exception.h"
26
#include "common/status.h"
27
#include "core/block/column_numbers.h"
28
#include "core/block/column_with_type_and_name.h"
29
#include "core/block/columns_with_type_and_name.h"
30
#include "core/column/column.h"
31
#include "core/column/column_const.h"
32
#include "exprs/function_context.h"
33
#include "exprs/vexpr.h"
34
#include "runtime/runtime_state.h"
35
#include "runtime/thread_context.h"
36
#include "storage/olap_common.h"
37
#include "storage/segment/column_reader.h"
38
#include "util/simd/bits.h"
39
40
namespace doris {
41
class RowDescriptor;
42
} // namespace doris
43
44
namespace doris {
45
#include "common/compile_check_begin.h"
46
47
31.4M
VExprContext::~VExprContext() {
48
    // In runtime filter, only create expr context to get expr root, will not call
49
    // prepare or open, so that it is not need to call close. And call close may core
50
    // because the function context in expr is not set.
51
31.4M
    if (!_prepared || !_opened) {
52
462k
        return;
53
462k
    }
54
31.0M
    try {
55
31.0M
        close();
56
31.0M
    } catch (const Exception& e) {
57
0
        LOG(WARNING) << "Exception occurs when expr context deconstruct: " << e.to_string();
58
0
    }
59
31.0M
}
60
61
1.48M
Status VExprContext::execute(Block* block, int* result_column_id) {
62
1.48M
    Status st;
63
1.48M
    RETURN_IF_CATCH_EXCEPTION({
64
1.48M
        st = _root->execute(this, block, result_column_id);
65
1.48M
        _last_result_column_id = *result_column_id;
66
        // We should first check the status, as some expressions might incorrectly set result_column_id, even if the st is not ok.
67
1.48M
        if (st.ok() && _last_result_column_id != -1) {
68
1.48M
            block->get_by_position(*result_column_id).column->sanity_check();
69
1.48M
            RETURN_IF_ERROR(
70
1.48M
                    block->get_by_position(*result_column_id).check_type_and_column_match());
71
1.48M
        }
72
1.48M
    });
73
1.48M
    return st;
74
1.48M
}
75
76
2.91M
Status VExprContext::execute(const Block* block, ColumnPtr& result_column) {
77
2.91M
    Status st;
78
2.91M
    RETURN_IF_CATCH_EXCEPTION(
79
2.91M
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
80
2.91M
    return st;
81
2.91M
}
82
83
28.0k
Status VExprContext::execute(const Block* block, ColumnWithTypeAndName& result_data) {
84
28.0k
    Status st;
85
28.0k
    ColumnPtr result_column;
86
28.0k
    RETURN_IF_CATCH_EXCEPTION(
87
28.0k
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
88
28.0k
    RETURN_IF_ERROR(st);
89
28.0k
    result_data.column = result_column;
90
28.0k
    result_data.type = execute_type(block);
91
28.0k
    result_data.name = _root->expr_name();
92
28.0k
    return Status::OK();
93
28.0k
}
94
95
1.35M
DataTypePtr VExprContext::execute_type(const Block* block) {
96
1.35M
    return _root->execute_type(block);
97
1.35M
}
98
99
1.13M
Status VExprContext::execute_const_expr(ColumnWithTypeAndName& result) {
100
1.13M
    Status st;
101
1.13M
    RETURN_IF_CATCH_EXCEPTION(
102
1.13M
            { st = _root->execute_column(this, nullptr, nullptr, 1, result.column); });
103
1.13M
    RETURN_IF_ERROR(st);
104
1.13M
    result.type = _root->execute_type(nullptr);
105
1.13M
    result.name = _root->expr_name();
106
1.13M
    return Status::OK();
107
1.13M
}
108
109
1.32M
[[nodiscard]] const std::string& VExprContext::expr_name() const {
110
1.32M
    return _root->expr_name();
111
1.32M
}
112
113
0
bool VExprContext::is_blockable() const {
114
0
    return _root->is_blockable();
115
0
}
116
117
7.84M
Status VExprContext::prepare(RuntimeState* state, const RowDescriptor& row_desc) {
118
7.84M
    _prepared = true;
119
7.84M
    Status st;
120
7.84M
    RETURN_IF_CATCH_EXCEPTION({ st = _root->prepare(state, row_desc, this); });
121
7.84M
    return st;
122
7.84M
}
123
124
7.84M
Status VExprContext::open(RuntimeState* state) {
125
7.84M
    DCHECK(_prepared);
126
7.84M
    if (_opened) {
127
39
        return Status::OK();
128
39
    }
129
7.84M
    _opened = true;
130
    // Fragment-local state is only initialized for original contexts. Clones inherit the
131
    // original's fragment state and only need to have thread-local state initialized.
132
7.84M
    FunctionContext::FunctionStateScope scope =
133
7.84M
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
134
7.84M
    Status st;
135
7.84M
    RETURN_IF_CATCH_EXCEPTION({ st = _root->open(state, this, scope); });
136
7.83M
    return st;
137
7.84M
}
138
139
31.0M
void VExprContext::close() {
140
    // Sometimes expr context may not have a root, then it need not call close
141
31.0M
    if (_root == nullptr) {
142
0
        return;
143
0
    }
144
31.0M
    FunctionContext::FunctionStateScope scope =
145
31.0M
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
146
31.0M
    _root->close(this, scope);
147
31.0M
}
148
149
23.0M
Status VExprContext::clone(RuntimeState* state, VExprContextSPtr& new_ctx) {
150
18.4E
    DCHECK(_prepared) << "expr context not prepared";
151
23.0M
    DCHECK(_opened);
152
23.0M
    DCHECK(new_ctx.get() == nullptr);
153
154
23.0M
    new_ctx = std::make_shared<VExprContext>(_root);
155
23.0M
    for (auto& _fn_context : _fn_contexts) {
156
1.45M
        new_ctx->_fn_contexts.push_back(_fn_context->clone());
157
1.45M
    }
158
159
23.0M
    new_ctx->_is_clone = true;
160
23.0M
    new_ctx->_prepared = true;
161
23.0M
    new_ctx->_opened = true;
162
    // segment_v2::AnnRangeSearchRuntime should be cloned as well.
163
    // The object of segment_v2::AnnRangeSearchRuntime is not shared by threads.
164
23.0M
    new_ctx->_ann_range_search_runtime = this->_ann_range_search_runtime;
165
166
23.0M
    return _root->open(state, new_ctx.get(), FunctionContext::THREAD_LOCAL);
167
23.0M
}
168
169
0
void VExprContext::clone_fn_contexts(VExprContext* other) {
170
0
    for (auto& _fn_context : _fn_contexts) {
171
0
        other->_fn_contexts.push_back(_fn_context->clone());
172
0
    }
173
0
}
174
175
int VExprContext::register_function_context(RuntimeState* state, const DataTypePtr& return_type,
176
866k
                                            const std::vector<DataTypePtr>& arg_types) {
177
866k
    _fn_contexts.push_back(FunctionContext::create_context(state, return_type, arg_types));
178
866k
    _fn_contexts.back()->set_check_overflow_for_decimal(state->check_overflow_for_decimal());
179
866k
    _fn_contexts.back()->set_enable_strict_mode(state->enable_strict_mode());
180
866k
    return static_cast<int>(_fn_contexts.size()) - 1;
181
866k
}
182
183
13.0k
Status VExprContext::evaluate_inverted_index(uint32_t segment_num_rows) {
184
13.0k
    Status st;
185
13.0k
    RETURN_IF_CATCH_EXCEPTION({ st = _root->evaluate_inverted_index(this, segment_num_rows); });
186
13.0k
    return st;
187
13.0k
}
188
189
12.6k
bool VExprContext::all_expr_inverted_index_evaluated() {
190
12.6k
    return _index_context->has_index_result_for_expr(_root.get());
191
12.6k
}
192
193
49
Status VExprContext::filter_block(VExprContext* vexpr_ctx, Block* block) {
194
49
    if (vexpr_ctx == nullptr || block->rows() == 0) {
195
0
        return Status::OK();
196
0
    }
197
49
    ColumnPtr filter_column;
198
49
    RETURN_IF_ERROR(vexpr_ctx->execute(block, filter_column));
199
49
    size_t filter_column_id = block->columns();
200
49
    block->insert({filter_column, vexpr_ctx->execute_type(block), "filter_column"});
201
49
    vexpr_ctx->_memory_usage = filter_column->allocated_bytes();
202
49
    return Block::filter_block(block, filter_column_id, filter_column_id);
203
49
}
204
205
Status VExprContext::filter_block(const VExprContextSPtrs& expr_contexts, Block* block,
206
34.9M
                                  size_t column_to_keep) {
207
34.9M
    if (expr_contexts.empty() || block->rows() == 0) {
208
34.8M
        return Status::OK();
209
34.8M
    }
210
211
41.9k
    ColumnNumbers columns_to_filter(column_to_keep);
212
41.9k
    std::iota(columns_to_filter.begin(), columns_to_filter.end(), 0);
213
214
41.9k
    return execute_conjuncts_and_filter_block(expr_contexts, block, columns_to_filter,
215
41.9k
                                              static_cast<int>(column_to_keep));
216
34.9M
}
217
218
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
219
                                       const std::vector<IColumn::Filter*>* filters, Block* block,
220
81.8k
                                       IColumn::Filter* result_filter, bool* can_filter_all) {
221
81.8k
    return execute_conjuncts(ctxs, filters, false, block, result_filter, can_filter_all);
222
81.8k
}
223
224
Status VExprContext::execute_filter(const Block* block, uint8_t* __restrict result_filter_data,
225
182k
                                    size_t rows, bool accept_null, bool* can_filter_all) {
226
182k
    return _root->execute_filter(this, block, result_filter_data, rows, accept_null,
227
182k
                                 can_filter_all);
228
182k
}
229
230
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
231
                                       const std::vector<IColumn::Filter*>* filters,
232
                                       bool accept_null, const Block* block,
233
138k
                                       IColumn::Filter* result_filter, bool* can_filter_all) {
234
138k
    size_t rows = block->rows();
235
138k
    DCHECK_EQ(result_filter->size(), rows);
236
138k
    *can_filter_all = false;
237
138k
    auto* __restrict result_filter_data = result_filter->data();
238
182k
    for (const auto& ctx : ctxs) {
239
182k
        RETURN_IF_ERROR(
240
182k
                ctx->execute_filter(block, result_filter_data, rows, accept_null, can_filter_all));
241
182k
        if (*can_filter_all) {
242
47.2k
            return Status::OK();
243
47.2k
        }
244
182k
    }
245
91.1k
    if (filters != nullptr) {
246
47.0k
        for (auto* filter : *filters) {
247
1.42k
            auto* __restrict filter_data = filter->data();
248
1.42k
            const size_t size = filter->size();
249
862k
            for (size_t i = 0; i < size; ++i) {
250
860k
                result_filter_data[i] &= filter_data[i];
251
860k
            }
252
1.42k
            if (memchr(result_filter_data, 0x1, size) == nullptr) {
253
934
                *can_filter_all = true;
254
934
                return Status::OK();
255
934
            }
256
1.42k
        }
257
47.0k
    }
258
90.2k
    return Status::OK();
259
91.1k
}
260
261
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& conjuncts, const Block* block,
262
378
                                       ColumnUInt8& null_map, IColumn::Filter& filter) {
263
378
    const auto& rows = block->rows();
264
378
    if (rows == 0) {
265
0
        return Status::OK();
266
0
    }
267
378
    if (null_map.size() != rows) {
268
0
        return Status::InternalError("null_map.size()!=rows, null_map.size()={}, rows={}",
269
0
                                     null_map.size(), rows);
270
0
    }
271
272
378
    auto* final_null_map = null_map.get_data().data();
273
378
    auto* final_filter_ptr = filter.data();
274
275
378
    for (const auto& conjunct : conjuncts) {
276
66
        ColumnPtr result_column;
277
66
        RETURN_IF_ERROR(conjunct->execute(block, result_column));
278
66
        auto [filter_column, is_const] = unpack_if_const(result_column);
279
66
        const auto* nullable_column = assert_cast<const ColumnNullable*>(filter_column.get());
280
66
        if (!is_const) {
281
57
            const ColumnPtr& nested_column = nullable_column->get_nested_column_ptr();
282
57
            const IColumn::Filter& result =
283
57
                    assert_cast<const ColumnUInt8&>(*nested_column).get_data();
284
57
            const auto* __restrict filter_data = result.data();
285
57
            const auto* __restrict null_map_data = nullable_column->get_null_map_data().data();
286
57
            DCHECK_EQ(rows, nullable_column->size());
287
288
634
            for (size_t i = 0; i != rows; ++i) {
289
                // null and null    => null
290
                // null and true    => null
291
                // null and false   => false
292
577
                final_null_map[i] = (final_null_map[i] & (null_map_data[i] | filter_data[i])) |
293
577
                                    (null_map_data[i] & (final_null_map[i] | final_filter_ptr[i]));
294
577
                final_filter_ptr[i] = final_filter_ptr[i] & filter_data[i];
295
577
            }
296
57
        } else {
297
9
            bool filter_data = nullable_column->get_bool(0);
298
9
            bool null_map_data = nullable_column->is_null_at(0);
299
28
            for (size_t i = 0; i != rows; ++i) {
300
                // null and null    => null
301
                // null and true    => null
302
                // null and false   => false
303
19
                final_null_map[i] = (final_null_map[i] & (null_map_data | filter_data)) |
304
19
                                    (null_map_data & (final_null_map[i] | final_filter_ptr[i]));
305
19
                final_filter_ptr[i] = final_filter_ptr[i] & filter_data;
306
19
            }
307
9
        }
308
66
    }
309
378
    return Status::OK();
310
378
}
311
312
// TODO Performance Optimization
313
// need exception safety
314
Status VExprContext::execute_conjuncts_and_filter_block(const VExprContextSPtrs& ctxs, Block* block,
315
                                                        std::vector<uint32_t>& columns_to_filter,
316
43.7k
                                                        int column_to_keep) {
317
43.7k
    IColumn::Filter result_filter(block->rows(), 1);
318
43.7k
    bool can_filter_all;
319
320
43.7k
    _reset_memory_usage(ctxs);
321
322
43.7k
    RETURN_IF_ERROR(
323
43.7k
            execute_conjuncts(ctxs, nullptr, false, block, &result_filter, &can_filter_all));
324
325
    // Accumulate the usage of `result_filter` into the first context.
326
43.7k
    if (!ctxs.empty()) {
327
43.7k
        ctxs[0]->_memory_usage += result_filter.allocated_bytes();
328
43.7k
    }
329
43.7k
    if (can_filter_all) {
330
62.7k
        for (auto& col : columns_to_filter) {
331
62.7k
            auto& column = block->get_by_position(col).column;
332
62.7k
            if (column->is_exclusive()) {
333
61.0k
                column->assume_mutable()->clear();
334
61.0k
            } else {
335
1.77k
                column = column->clone_empty();
336
1.77k
            }
337
62.7k
        }
338
29.5k
    } else {
339
29.5k
        try {
340
29.5k
            Block::filter_block_internal(block, columns_to_filter, result_filter);
341
29.5k
        } catch (const Exception& e) {
342
0
            std::string str;
343
0
            for (auto ctx : ctxs) {
344
0
                if (str.length()) {
345
0
                    str += ",";
346
0
                }
347
0
                str += ctx->root()->debug_string();
348
0
            }
349
350
0
            return Status::InternalError(
351
0
                    "filter_block_internal meet exception, exprs=[{}], exception={}", str,
352
0
                    e.what());
353
0
        }
354
29.5k
    }
355
43.7k
    Block::erase_useless_column(block, column_to_keep);
356
43.7k
    return Status::OK();
357
43.7k
}
358
359
Status VExprContext::execute_conjuncts_and_filter_block(const VExprContextSPtrs& ctxs, Block* block,
360
                                                        std::vector<uint32_t>& columns_to_filter,
361
                                                        int column_to_keep,
362
6.61k
                                                        IColumn::Filter& filter) {
363
6.61k
    _reset_memory_usage(ctxs);
364
6.61k
    filter.resize_fill(block->rows(), 1);
365
6.61k
    bool can_filter_all;
366
6.61k
    RETURN_IF_ERROR(execute_conjuncts(ctxs, nullptr, false, block, &filter, &can_filter_all));
367
368
    // Accumulate the usage of `result_filter` into the first context.
369
6.61k
    if (!ctxs.empty()) {
370
6.57k
        ctxs[0]->_memory_usage += filter.allocated_bytes();
371
6.57k
    }
372
6.61k
    if (can_filter_all) {
373
4.76k
        for (auto& col : columns_to_filter) {
374
4.76k
            auto& column = block->get_by_position(col).column;
375
4.76k
            if (column->is_exclusive()) {
376
4.63k
                column->assume_mutable()->clear();
377
4.63k
            } else {
378
134
                column = column->clone_empty();
379
134
            }
380
4.76k
        }
381
4.27k
    } else {
382
4.27k
        RETURN_IF_CATCH_EXCEPTION(Block::filter_block_internal(block, columns_to_filter, filter));
383
4.27k
    }
384
385
6.61k
    Block::erase_useless_column(block, column_to_keep);
386
6.61k
    return Status::OK();
387
6.61k
}
388
389
// do_projection: for some query(e.g. in MultiCastDataStreamerSourceOperator::get_block()),
390
// output_vexpr_ctxs will output the same column more than once, and if the output_block
391
// is mem-reused later, it will trigger DCHECK_EQ(d.column->use_count(), 1) failure when
392
// doing Block::clear_column_data, set do_projection to true to copy the column data to
393
// avoid this problem.
394
Status VExprContext::get_output_block_after_execute_exprs(
395
        const VExprContextSPtrs& output_vexpr_ctxs, const Block& input_block, Block* output_block,
396
219k
        bool do_projection) {
397
219k
    auto rows = input_block.rows();
398
219k
    ColumnsWithTypeAndName result_columns;
399
219k
    _reset_memory_usage(output_vexpr_ctxs);
400
401
1.32M
    for (const auto& vexpr_ctx : output_vexpr_ctxs) {
402
1.32M
        ColumnPtr result_column;
403
1.32M
        RETURN_IF_ERROR(vexpr_ctx->execute(&input_block, result_column));
404
405
1.32M
        auto type = vexpr_ctx->execute_type(&input_block);
406
1.32M
        const auto& name = vexpr_ctx->expr_name();
407
408
1.32M
        vexpr_ctx->_memory_usage += result_column->allocated_bytes();
409
1.32M
        if (do_projection) {
410
22.0k
            result_columns.emplace_back(result_column->clone_resized(rows), type, name);
411
412
1.30M
        } else {
413
1.30M
            result_columns.emplace_back(result_column, type, name);
414
1.30M
        }
415
1.32M
    }
416
219k
    *output_block = {result_columns};
417
219k
    return Status::OK();
418
219k
}
419
420
270k
void VExprContext::_reset_memory_usage(const VExprContextSPtrs& contexts) {
421
270k
    std::for_each(contexts.begin(), contexts.end(),
422
1.39M
                  [](auto&& context) { context->_memory_usage = 0; });
423
270k
}
424
425
12.0k
void VExprContext::prepare_ann_range_search(const doris::VectorSearchUserParams& params) {
426
12.0k
    if (_root == nullptr) {
427
0
        return;
428
0
    }
429
430
12.0k
    _root->prepare_ann_range_search(params, _ann_range_search_runtime, _suitable_for_ann_index);
431
18.4E
    VLOG_DEBUG << fmt::format("Prepare ann range search result {}, _suitable_for_ann_index {}",
432
18.4E
                              this->_ann_range_search_runtime.to_string(),
433
18.4E
                              this->_suitable_for_ann_index);
434
12.0k
    return;
435
12.0k
}
436
437
Status VExprContext::evaluate_ann_range_search(
438
        const std::vector<std::unique_ptr<segment_v2::IndexIterator>>& cid_to_index_iterators,
439
        const std::vector<ColumnId>& idx_to_cid,
440
        const std::vector<std::unique_ptr<segment_v2::ColumnIterator>>& column_iterators,
441
        const std::unordered_map<VExprContext*, std::unordered_map<ColumnId, VExpr*>>&
442
                common_expr_to_slotref_map,
443
12.7k
        roaring::Roaring& row_bitmap, segment_v2::AnnIndexStats& ann_index_stats) {
444
12.7k
    if (_root == nullptr) {
445
0
        return Status::OK();
446
0
    }
447
448
12.7k
    RETURN_IF_ERROR(_root->evaluate_ann_range_search(
449
12.7k
            _ann_range_search_runtime, cid_to_index_iterators, idx_to_cid, column_iterators,
450
12.7k
            row_bitmap, ann_index_stats));
451
452
12.7k
    if (!_root->ann_range_search_executedd()) {
453
12.7k
        return Status::OK();
454
12.7k
    }
455
456
49
    if (!_root->ann_dist_is_fulfilled()) {
457
        // Do not perform index scan in this case.
458
9
        return Status::OK();
459
9
    }
460
461
40
    auto src_col_idx = _ann_range_search_runtime.src_col_idx;
462
40
    auto slot_ref_map_it = common_expr_to_slotref_map.find(this);
463
40
    if (slot_ref_map_it == common_expr_to_slotref_map.end()) {
464
1
        return Status::OK();
465
1
    }
466
39
    auto& slot_ref_map = slot_ref_map_it->second;
467
39
    ColumnId cid = idx_to_cid[src_col_idx];
468
39
    if (slot_ref_map.find(cid) == slot_ref_map.end()) {
469
6
        return Status::OK();
470
6
    }
471
33
    const VExpr* slot_ref_expr_addr = slot_ref_map.find(cid)->second;
472
33
    _index_context->set_true_for_index_status(slot_ref_expr_addr, idx_to_cid[cid]);
473
474
18.4E
    VLOG_DEBUG << fmt::format(
475
18.4E
            "Evaluate ann range search for expr {}, src_col_idx {}, cid {}, row_bitmap "
476
18.4E
            "cardinality {}",
477
18.4E
            _root->debug_string(), src_col_idx, cid, row_bitmap.cardinality());
478
33
    return Status::OK();
479
39
}
480
481
596k
uint64_t VExprContext::get_digest(uint64_t seed) const {
482
596k
    return _root->get_digest(seed);
483
596k
}
484
485
1.24M
double VExprContext::execute_cost() const {
486
1.24M
    if (_root == nullptr) {
487
        // When there is no expression root, treat the cost as a base value.
488
        // This avoids null dereferences while keeping a deterministic cost.
489
0
        return 0.0;
490
0
    }
491
1.24M
    return _root->execute_cost();
492
1.24M
}
493
494
#include "common/compile_check_end.h"
495
} // namespace doris