Coverage Report

Created: 2026-04-15 12:36

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
655k
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
655k
    if (!_prepared || !_opened) {
51
141k
        return;
52
141k
    }
53
513k
    try {
54
513k
        close();
55
513k
    } catch (const Exception& e) {
56
0
        LOG(WARNING) << "Exception occurs when expr context deconstruct: " << e.to_string();
57
0
    }
58
513k
}
59
60
189k
Status VExprContext::execute(Block* block, int* result_column_id) {
61
189k
    Status st;
62
189k
    RETURN_IF_CATCH_EXCEPTION({
63
189k
        st = _root->execute(this, block, result_column_id);
64
189k
        _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
189k
        if (st.ok() && _last_result_column_id != -1) {
67
189k
            block->get_by_position(*result_column_id).column->sanity_check();
68
189k
            RETURN_IF_ERROR(
69
189k
                    block->get_by_position(*result_column_id).check_type_and_column_match());
70
189k
        }
71
189k
    });
72
189k
    return st;
73
189k
}
74
75
276
Status VExprContext::execute(const Block* block, ColumnPtr& result_column) {
76
276
    Status st;
77
276
    RETURN_IF_CATCH_EXCEPTION(
78
276
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
79
276
    return st;
80
276
}
81
82
19
Status VExprContext::execute(const Block* block, ColumnWithTypeAndName& result_data) {
83
19
    Status st;
84
19
    ColumnPtr result_column;
85
19
    RETURN_IF_CATCH_EXCEPTION(
86
19
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
87
19
    RETURN_IF_ERROR(st);
88
19
    result_data.column = result_column;
89
19
    result_data.type = execute_type(block);
90
19
    result_data.name = _root->expr_name();
91
19
    return Status::OK();
92
19
}
93
94
39
DataTypePtr VExprContext::execute_type(const Block* block) {
95
39
    return _root->execute_type(block);
96
39
}
97
98
30
Status VExprContext::execute_const_expr(ColumnWithTypeAndName& result) {
99
30
    Status st;
100
30
    RETURN_IF_CATCH_EXCEPTION(
101
30
            { st = _root->execute_column(this, nullptr, nullptr, 1, result.column); });
102
30
    RETURN_IF_ERROR(st);
103
30
    result.type = _root->execute_type(nullptr);
104
30
    result.name = _root->expr_name();
105
30
    return Status::OK();
106
30
}
107
108
42
[[nodiscard]] const std::string& VExprContext::expr_name() const {
109
42
    return _root->expr_name();
110
42
}
111
112
0
bool VExprContext::is_blockable() const {
113
0
    return _root->is_blockable();
114
0
}
115
116
258k
Status VExprContext::prepare(RuntimeState* state, const RowDescriptor& row_desc) {
117
258k
    _prepared = true;
118
258k
    Status st;
119
258k
    RETURN_IF_CATCH_EXCEPTION({ st = _root->prepare(state, row_desc, this); });
120
258k
    return st;
121
258k
}
122
123
258k
Status VExprContext::open(RuntimeState* state) {
124
258k
    DCHECK(_prepared);
125
258k
    if (_opened) {
126
13
        return Status::OK();
127
13
    }
128
258k
    _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
258k
    FunctionContext::FunctionStateScope scope =
132
258k
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
133
258k
    Status st;
134
258k
    RETURN_IF_CATCH_EXCEPTION({ st = _root->open(state, this, scope); });
135
258k
    return st;
136
258k
}
137
138
513k
void VExprContext::close() {
139
    // Sometimes expr context may not have a root, then it need not call close
140
513k
    if (_root == nullptr) {
141
0
        return;
142
0
    }
143
513k
    FunctionContext::FunctionStateScope scope =
144
513k
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
145
513k
    _root->close(this, scope);
146
513k
}
147
148
254k
Status VExprContext::clone(RuntimeState* state, VExprContextSPtr& new_ctx) {
149
254k
    DCHECK(_prepared) << "expr context not prepared";
150
254k
    DCHECK(_opened);
151
254k
    DCHECK(new_ctx.get() == nullptr);
152
153
254k
    new_ctx = std::make_shared<VExprContext>(_root);
154
254k
    for (auto& _fn_context : _fn_contexts) {
155
19
        new_ctx->_fn_contexts.push_back(_fn_context->clone());
156
19
    }
157
158
254k
    new_ctx->_is_clone = true;
159
254k
    new_ctx->_prepared = true;
160
254k
    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
254k
    new_ctx->_ann_range_search_runtime = this->_ann_range_search_runtime;
164
165
254k
    return _root->open(state, new_ctx.get(), FunctionContext::THREAD_LOCAL);
166
254k
}
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
103
                                            const std::vector<DataTypePtr>& arg_types) {
176
103
    _fn_contexts.push_back(FunctionContext::create_context(state, return_type, arg_types));
177
103
    _fn_contexts.back()->set_check_overflow_for_decimal(state->check_overflow_for_decimal());
178
103
    _fn_contexts.back()->set_enable_strict_mode(state->enable_strict_mode());
179
103
    return static_cast<int>(_fn_contexts.size()) - 1;
180
103
}
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
1.05k
                                  size_t column_to_keep) {
206
1.05k
    if (expr_contexts.empty() || block->rows() == 0) {
207
1.04k
        return Status::OK();
208
1.04k
    }
209
210
5
    ColumnNumbers columns_to_filter(column_to_keep);
211
5
    std::iota(columns_to_filter.begin(), columns_to_filter.end(), 0);
212
213
5
    return execute_conjuncts_and_filter_block(expr_contexts, block, columns_to_filter,
214
5
                                              static_cast<int>(column_to_keep));
215
1.05k
}
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
31
                                    size_t rows, bool accept_null, bool* can_filter_all) {
225
31
    return _root->execute_filter(this, block, result_filter_data, rows, accept_null,
226
31
                                 can_filter_all);
227
31
}
228
229
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
230
                                       const std::vector<IColumn::Filter*>* filters,
231
                                       bool accept_null, const Block* block,
232
23
                                       IColumn::Filter* result_filter, bool* can_filter_all) {
233
23
    size_t rows = block->rows();
234
23
    DCHECK_EQ(result_filter->size(), rows);
235
23
    *can_filter_all = false;
236
23
    auto* __restrict result_filter_data = result_filter->data();
237
31
    for (const auto& ctx : ctxs) {
238
31
        RETURN_IF_ERROR(
239
31
                ctx->execute_filter(block, result_filter_data, rows, accept_null, can_filter_all));
240
31
        if (*can_filter_all) {
241
10
            return Status::OK();
242
10
        }
243
31
    }
244
13
    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
13
    return Status::OK();
258
13
}
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
5
                                                        int column_to_keep) {
316
5
    IColumn::Filter result_filter(block->rows(), 1);
317
5
    bool can_filter_all;
318
319
5
    _reset_memory_usage(ctxs);
320
321
5
    RETURN_IF_ERROR(
322
5
            execute_conjuncts(ctxs, nullptr, false, block, &result_filter, &can_filter_all));
323
324
    // Accumulate the usage of `result_filter` into the first context.
325
5
    if (!ctxs.empty()) {
326
5
        ctxs[0]->_memory_usage += result_filter.allocated_bytes();
327
5
    }
328
5
    if (can_filter_all) {
329
3
        for (auto& col : columns_to_filter) {
330
3
            auto& column = block->get_by_position(col).column;
331
3
            if (column->is_exclusive()) {
332
0
                column->assume_mutable()->clear();
333
3
            } else {
334
3
                column = column->clone_empty();
335
3
            }
336
3
        }
337
4
    } else {
338
4
        try {
339
4
            Block::filter_block_internal(block, columns_to_filter, result_filter);
340
4
        } 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
4
    }
354
5
    Block::erase_useless_column(block, column_to_keep);
355
5
    return Status::OK();
356
5
}
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
4
        bool do_projection) {
396
4
    auto rows = input_block.rows();
397
4
    ColumnsWithTypeAndName result_columns;
398
4
    _reset_memory_usage(output_vexpr_ctxs);
399
400
20
    for (const auto& vexpr_ctx : output_vexpr_ctxs) {
401
20
        ColumnPtr result_column;
402
20
        RETURN_IF_ERROR(vexpr_ctx->execute(&input_block, result_column));
403
404
20
        auto type = vexpr_ctx->execute_type(&input_block);
405
20
        const auto& name = vexpr_ctx->expr_name();
406
407
20
        vexpr_ctx->_memory_usage += result_column->allocated_bytes();
408
20
        if (do_projection) {
409
0
            result_columns.emplace_back(result_column->clone_resized(rows), type, name);
410
411
20
        } else {
412
20
            result_columns.emplace_back(result_column, type, name);
413
20
        }
414
20
    }
415
4
    *output_block = {result_columns};
416
4
    return Status::OK();
417
4
}
418
419
11
void VExprContext::_reset_memory_usage(const VExprContextSPtrs& contexts) {
420
11
    std::for_each(contexts.begin(), contexts.end(),
421
27
                  [](auto&& context) { context->_memory_usage = 0; });
422
11
}
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
0
uint64_t VExprContext::get_digest(uint64_t seed) const {
481
0
    return _root->get_digest(seed);
482
0
}
483
484
16
double VExprContext::execute_cost() const {
485
16
    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
16
    return _root->execute_cost();
491
16
}
492
493
} // namespace doris