Coverage Report

Created: 2026-05-29 11:01

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 "exec/common/util.hpp"
33
#include "exprs/function_context.h"
34
#include "exprs/vexpr.h"
35
#include "runtime/runtime_state.h"
36
#include "runtime/thread_context.h"
37
#include "storage/olap_common.h"
38
#include "storage/segment/column_reader.h"
39
#include "util/simd/bits.h"
40
41
namespace doris {
42
class RowDescriptor;
43
} // namespace doris
44
45
namespace doris {
46
47
706k
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
706k
    if (!_prepared || !_opened) {
52
141k
        return;
53
141k
    }
54
564k
    try {
55
564k
        close();
56
564k
    } catch (const Exception& e) {
57
0
        LOG(WARNING) << "Exception occurs when expr context deconstruct: " << e.to_string();
58
0
    }
59
564k
}
60
61
189k
Status VExprContext::execute(Block* block, int* result_column_id) {
62
189k
    Status st;
63
189k
    RETURN_IF_CATCH_EXCEPTION({
64
189k
        st = _root->execute(this, block, result_column_id);
65
189k
        _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
189k
        if (st.ok() && _last_result_column_id != -1) {
68
189k
            block->get_by_position(*result_column_id).column->sanity_check();
69
189k
            RETURN_IF_ERROR(
70
189k
                    block->get_by_position(*result_column_id).check_type_and_column_match());
71
189k
        }
72
189k
    });
73
189k
    return st;
74
189k
}
75
76
5.00k
Status VExprContext::execute(const Block* block, ColumnPtr& result_column) {
77
5.00k
    Status st;
78
5.00k
    RETURN_IF_CATCH_EXCEPTION(
79
5.00k
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
80
5.00k
    return st;
81
5.00k
}
82
83
85
Status VExprContext::execute(const Block* block, ColumnWithTypeAndName& result_data) {
84
85
    Status st;
85
85
    ColumnPtr result_column;
86
85
    RETURN_IF_CATCH_EXCEPTION(
87
85
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
88
85
    RETURN_IF_ERROR(st);
89
85
    result_data.column = result_column;
90
85
    result_data.type = execute_type(block);
91
85
    result_data.name = _root->expr_name();
92
85
    return Status::OK();
93
85
}
94
95
1.37k
DataTypePtr VExprContext::execute_type(const Block* block) {
96
1.37k
    return _root->execute_type(block);
97
1.37k
}
98
99
240
Status VExprContext::execute_const_expr(ColumnWithTypeAndName& result) {
100
240
    Status st;
101
240
    RETURN_IF_CATCH_EXCEPTION(
102
240
            { st = _root->execute_column(this, nullptr, nullptr, 1, result.column); });
103
240
    RETURN_IF_ERROR(st);
104
240
    result.type = _root->execute_type(nullptr);
105
240
    result.name = _root->expr_name();
106
240
    return Status::OK();
107
240
}
108
109
1.21k
[[nodiscard]] const std::string& VExprContext::expr_name() const {
110
1.21k
    return _root->expr_name();
111
1.21k
}
112
113
0
bool VExprContext::is_blockable() const {
114
0
    return _root->is_blockable();
115
0
}
116
117
268k
Status VExprContext::prepare(RuntimeState* state, const RowDescriptor& row_desc) {
118
268k
    _prepared = true;
119
268k
    Status st;
120
268k
    RETURN_IF_CATCH_EXCEPTION({ st = _root->prepare(state, row_desc, this); });
121
268k
    return st;
122
268k
}
123
124
268k
Status VExprContext::open(RuntimeState* state) {
125
268k
    DCHECK(_prepared);
126
268k
    if (_opened) {
127
13
        return Status::OK();
128
13
    }
129
268k
    _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
268k
    FunctionContext::FunctionStateScope scope =
133
268k
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
134
268k
    Status st;
135
268k
    RETURN_IF_CATCH_EXCEPTION({ st = _root->open(state, this, scope); });
136
268k
    return st;
137
268k
}
138
139
564k
void VExprContext::close() {
140
    // Sometimes expr context may not have a root, then it need not call close
141
564k
    if (_root == nullptr) {
142
0
        return;
143
0
    }
144
564k
    FunctionContext::FunctionStateScope scope =
145
564k
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
146
564k
    _root->close(this, scope);
147
564k
}
148
149
295k
Status VExprContext::clone(RuntimeState* state, VExprContextSPtr& new_ctx) {
150
18.4E
    DCHECK(_prepared) << "expr context not prepared";
151
295k
    DCHECK(_opened);
152
295k
    DCHECK(new_ctx.get() == nullptr);
153
154
295k
    new_ctx = std::make_shared<VExprContext>(_root);
155
295k
    for (auto& _fn_context : _fn_contexts) {
156
1.23k
        new_ctx->_fn_contexts.push_back(_fn_context->clone());
157
1.23k
    }
158
159
295k
    new_ctx->_is_clone = true;
160
295k
    new_ctx->_prepared = true;
161
295k
    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
295k
    new_ctx->_ann_range_search_runtime = this->_ann_range_search_runtime;
165
166
295k
    return _root->open(state, new_ctx.get(), FunctionContext::THREAD_LOCAL);
167
295k
}
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
1.47k
                                            const std::vector<DataTypePtr>& arg_types) {
177
1.47k
    _fn_contexts.push_back(FunctionContext::create_context(state, return_type, arg_types));
178
1.47k
    _fn_contexts.back()->set_check_overflow_for_decimal(state->check_overflow_for_decimal());
179
1.47k
    _fn_contexts.back()->set_enable_strict_mode(state->enable_strict_mode());
180
1.47k
    return static_cast<int>(_fn_contexts.size()) - 1;
181
1.47k
}
182
183
0
Status VExprContext::evaluate_inverted_index(uint32_t segment_num_rows) {
184
0
    Status st;
185
0
    RETURN_IF_CATCH_EXCEPTION({ st = _root->evaluate_inverted_index(this, segment_num_rows); });
186
0
    return st;
187
0
}
188
189
0
bool VExprContext::all_expr_inverted_index_evaluated() {
190
0
    return _index_context->has_index_result_for_expr(_root.get());
191
0
}
192
193
0
Status VExprContext::filter_block(VExprContext* vexpr_ctx, Block* block) {
194
0
    if (vexpr_ctx == nullptr || block->rows() == 0) {
195
0
        return Status::OK();
196
0
    }
197
0
    ColumnPtr filter_column;
198
0
    RETURN_IF_ERROR(vexpr_ctx->execute(block, filter_column));
199
0
    size_t filter_column_id = block->columns();
200
0
    block->insert({filter_column, vexpr_ctx->execute_type(block), "filter_column"});
201
0
    vexpr_ctx->_memory_usage = filter_column->allocated_bytes();
202
0
    return Block::filter_block(block, filter_column_id, filter_column_id);
203
0
}
204
205
Status VExprContext::filter_block(const VExprContextSPtrs& expr_contexts, Block* block,
206
2.53k
                                  size_t column_to_keep) {
207
2.53k
    if (expr_contexts.empty() || block->rows() == 0) {
208
2.49k
        return Status::OK();
209
2.49k
    }
210
211
49
    ColumnNumbers columns_to_filter(column_to_keep);
212
49
    std::iota(columns_to_filter.begin(), columns_to_filter.end(), 0);
213
214
49
    return execute_conjuncts_and_filter_block(expr_contexts, block, columns_to_filter,
215
49
                                              static_cast<int>(column_to_keep));
216
2.53k
}
217
218
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
219
                                       const std::vector<IColumn::Filter*>* filters, Block* block,
220
48
                                       IColumn::Filter* result_filter, bool* can_filter_all) {
221
48
    return execute_conjuncts(ctxs, filters, false, block, result_filter, can_filter_all);
222
48
}
223
224
Status VExprContext::execute_filter(const Block* block, uint8_t* __restrict result_filter_data,
225
127
                                    size_t rows, bool accept_null, bool* can_filter_all) {
226
127
    return _root->execute_filter(this, block, result_filter_data, rows, accept_null,
227
127
                                 can_filter_all);
228
127
}
229
230
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
231
                                       const std::vector<IColumn::Filter*>* filters,
232
                                       bool accept_null, const Block* block,
233
131
                                       IColumn::Filter* result_filter, bool* can_filter_all) {
234
131
    size_t rows = block->rows();
235
131
    DCHECK_EQ(result_filter->size(), rows);
236
131
    *can_filter_all = false;
237
131
    auto* __restrict result_filter_data = result_filter->data();
238
131
    for (const auto& ctx : ctxs) {
239
127
        RETURN_IF_ERROR(
240
127
                ctx->execute_filter(block, result_filter_data, rows, accept_null, can_filter_all));
241
127
        if (*can_filter_all) {
242
26
            return Status::OK();
243
26
        }
244
127
    }
245
105
    if (filters != nullptr) {
246
22
        for (auto* filter : *filters) {
247
0
            auto* __restrict filter_data = filter->data();
248
0
            const size_t size = filter->size();
249
0
            for (size_t i = 0; i < size; ++i) {
250
0
                result_filter_data[i] &= filter_data[i];
251
0
            }
252
0
            if (memchr(result_filter_data, 0x1, size) == nullptr) {
253
0
                *can_filter_all = true;
254
0
                return Status::OK();
255
0
            }
256
0
        }
257
22
    }
258
105
    return Status::OK();
259
105
}
260
261
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& conjuncts, const Block* block,
262
6
                                       ColumnUInt8& null_map, IColumn::Filter& filter) {
263
6
    const auto& rows = block->rows();
264
6
    if (rows == 0) {
265
0
        return Status::OK();
266
0
    }
267
6
    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
6
    auto* final_null_map = null_map.get_data().data();
273
6
    auto* final_filter_ptr = filter.data();
274
275
6
    for (const auto& conjunct : conjuncts) {
276
4
        ColumnPtr result_column;
277
4
        RETURN_IF_ERROR(conjunct->execute(block, result_column));
278
4
        auto [filter_column, is_const] = unpack_if_const(result_column);
279
4
        const auto* nullable_column = assert_cast<const ColumnNullable*>(filter_column.get());
280
4
        if (!is_const) {
281
4
            const ColumnPtr& nested_column = nullable_column->get_nested_column_ptr();
282
4
            const IColumn::Filter& result =
283
4
                    assert_cast<const ColumnUInt8&>(*nested_column).get_data();
284
4
            const auto* __restrict filter_data = result.data();
285
4
            const auto* __restrict null_map_data = nullable_column->get_null_map_data().data();
286
4
            DCHECK_EQ(rows, nullable_column->size());
287
288
32
            for (size_t i = 0; i != rows; ++i) {
289
                // null and null    => null
290
                // null and true    => null
291
                // null and false   => false
292
28
                final_null_map[i] = (final_null_map[i] & (null_map_data[i] | filter_data[i])) |
293
28
                                    (null_map_data[i] & (final_null_map[i] | final_filter_ptr[i]));
294
28
                final_filter_ptr[i] = final_filter_ptr[i] & filter_data[i];
295
28
            }
296
4
        } else {
297
0
            bool filter_data = nullable_column->get_bool(0);
298
0
            bool null_map_data = nullable_column->is_null_at(0);
299
0
            for (size_t i = 0; i != rows; ++i) {
300
                // null and null    => null
301
                // null and true    => null
302
                // null and false   => false
303
0
                final_null_map[i] = (final_null_map[i] & (null_map_data | filter_data)) |
304
0
                                    (null_map_data & (final_null_map[i] | final_filter_ptr[i]));
305
0
                final_filter_ptr[i] = final_filter_ptr[i] & filter_data;
306
0
            }
307
0
        }
308
4
    }
309
6
    return Status::OK();
310
6
}
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
53
                                                        int column_to_keep) {
317
53
    IColumn::Filter result_filter(block->rows(), 1);
318
53
    bool can_filter_all;
319
320
53
    _reset_memory_usage(ctxs);
321
322
53
    RETURN_IF_ERROR(
323
53
            execute_conjuncts(ctxs, nullptr, false, block, &result_filter, &can_filter_all));
324
325
    // Accumulate the usage of `result_filter` into the first context.
326
53
    if (!ctxs.empty()) {
327
53
        ctxs[0]->_memory_usage += result_filter.allocated_bytes();
328
53
    }
329
53
    if (can_filter_all) {
330
3
        for (auto& col : columns_to_filter) {
331
3
            auto& column = block->get_by_position(col).column;
332
3
            if (column->is_exclusive()) {
333
3
                column->assert_mutable()->clear();
334
3
            } else {
335
0
                column = column->clone_empty();
336
0
            }
337
3
        }
338
52
    } else {
339
52
        try {
340
52
            Block::filter_block_internal(block, columns_to_filter, result_filter);
341
52
        } 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
52
    }
355
53
    Block::erase_useless_column(block, column_to_keep);
356
53
    return Status::OK();
357
53
}
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
2
                                                        IColumn::Filter& filter) {
363
2
    _reset_memory_usage(ctxs);
364
2
    filter.resize_fill(block->rows(), 1);
365
2
    bool can_filter_all;
366
2
    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
2
    if (!ctxs.empty()) {
370
2
        ctxs[0]->_memory_usage += filter.allocated_bytes();
371
2
    }
372
2
    if (can_filter_all) {
373
3
        for (auto& col : columns_to_filter) {
374
3
            auto& column = block->get_by_position(col).column;
375
3
            if (column->is_exclusive()) {
376
3
                column->assert_mutable()->clear();
377
3
            } else {
378
0
                column = column->clone_empty();
379
0
            }
380
3
        }
381
1
    } else {
382
1
        RETURN_IF_CATCH_EXCEPTION(Block::filter_block_internal(block, columns_to_filter, filter));
383
1
    }
384
385
2
    Block::erase_useless_column(block, column_to_keep);
386
2
    return Status::OK();
387
2
}
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
247
        bool do_projection) {
397
247
    auto rows = input_block.rows();
398
247
    ColumnsWithTypeAndName result_columns;
399
247
    _reset_memory_usage(output_vexpr_ctxs);
400
401
1.19k
    for (const auto& vexpr_ctx : output_vexpr_ctxs) {
402
1.19k
        ColumnPtr result_column;
403
1.19k
        RETURN_IF_ERROR(vexpr_ctx->execute(&input_block, result_column));
404
405
1.19k
        auto type = vexpr_ctx->execute_type(&input_block);
406
1.19k
        const auto& name = vexpr_ctx->expr_name();
407
408
1.19k
        vexpr_ctx->_memory_usage += result_column->allocated_bytes();
409
1.19k
        if (do_projection) {
410
130
            result_columns.emplace_back(result_column->clone_resized(rows), type, name);
411
412
1.06k
        } else {
413
1.06k
            result_columns.emplace_back(result_column, type, name);
414
1.06k
        }
415
1.19k
    }
416
247
    *output_block = {result_columns};
417
247
    return Status::OK();
418
247
}
419
420
302
void VExprContext::_reset_memory_usage(const VExprContextSPtrs& contexts) {
421
302
    std::for_each(contexts.begin(), contexts.end(),
422
1.24k
                  [](auto&& context) { context->_memory_usage = 0; });
423
302
}
424
425
7
void VExprContext::prepare_ann_range_search(const doris::VectorSearchUserParams& params) {
426
7
    if (_root == nullptr) {
427
0
        return;
428
0
    }
429
430
7
    _root->prepare_ann_range_search(params, _ann_range_search_runtime, _suitable_for_ann_index);
431
7
    VLOG_DEBUG << fmt::format("Prepare ann range search result {}, _suitable_for_ann_index {}",
432
0
                              this->_ann_range_search_runtime.to_string(),
433
0
                              this->_suitable_for_ann_index);
434
7
    return;
435
7
}
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
        roaring::Roaring& row_bitmap, segment_v2::AnnIndexStats& ann_index_stats,
444
6
        bool enable_result_cache, bool* ann_range_search_executed) {
445
6
    if (ann_range_search_executed != nullptr) {
446
5
        *ann_range_search_executed = false;
447
5
    }
448
6
    if (_root == nullptr) {
449
0
        return Status::OK();
450
0
    }
451
452
6
    AnnRangeSearchEvaluationResult evaluation_result;
453
6
    RETURN_IF_ERROR(_root->evaluate_ann_range_search(
454
6
            _ann_range_search_runtime, cid_to_index_iterators, idx_to_cid, column_iterators,
455
6
            row_bitmap, ann_index_stats, enable_result_cache, evaluation_result));
456
457
5
    if (!evaluation_result.executed) {
458
1
        return Status::OK();
459
1
    }
460
4
    if (ann_range_search_executed != nullptr) {
461
4
        *ann_range_search_executed = true;
462
4
    }
463
464
4
    DCHECK(_index_context != nullptr);
465
4
    _index_context->set_index_result_for_expr(
466
4
            _root.get(),
467
4
            segment_v2::InvertedIndexResultBitmap(std::make_shared<roaring::Roaring>(row_bitmap),
468
4
                                                  std::make_shared<roaring::Roaring>()));
469
470
4
    if (!evaluation_result.dist_fulfilled) {
471
        // Do not perform index scan in this case.
472
2
        return Status::OK();
473
2
    }
474
475
4
    DCHECK_LT(_ann_range_search_runtime.src_col_idx, idx_to_cid.size());
476
2
    const auto src_col_idx = cast_set<int>(_ann_range_search_runtime.src_col_idx);
477
2
    const auto src_col_key = cast_set<ColumnId>(_ann_range_search_runtime.src_col_idx);
478
2
    auto slot_ref_map_it = common_expr_to_slotref_map.find(this);
479
2
    if (slot_ref_map_it == common_expr_to_slotref_map.end()) {
480
1
        return Status::OK();
481
1
    }
482
1
    auto& slot_ref_map = slot_ref_map_it->second;
483
1
    auto slot_ref_it = slot_ref_map.find(src_col_key);
484
1
    if (slot_ref_it == slot_ref_map.end()) {
485
0
        return Status::OK();
486
0
    }
487
1
    const VExpr* slot_ref_expr_addr = slot_ref_it->second;
488
1
    _index_context->set_true_for_index_status(slot_ref_expr_addr, src_col_idx);
489
490
1
    VLOG_DEBUG << fmt::format(
491
0
            "Evaluate ann range search for expr {}, src_col_idx {}, cid {}, row_bitmap "
492
0
            "cardinality {}",
493
0
            _root->debug_string(), src_col_idx, idx_to_cid[_ann_range_search_runtime.src_col_idx],
494
0
            row_bitmap.cardinality());
495
1
    return Status::OK();
496
1
}
497
498
812
uint64_t VExprContext::get_digest(uint64_t seed) const {
499
812
    return _root->get_digest(seed);
500
812
}
501
502
2.30k
double VExprContext::execute_cost() const {
503
2.30k
    if (_root == nullptr) {
504
        // When there is no expression root, treat the cost as a base value.
505
        // This avoids null dereferences while keeping a deterministic cost.
506
0
        return 0.0;
507
0
    }
508
2.30k
    return _root->execute_cost();
509
2.30k
}
510
511
} // namespace doris