Coverage Report

Created: 2026-04-27 12:31

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