Coverage Report

Created: 2026-05-28 04:38

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
19.0M
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
19.0M
    if (!_prepared || !_opened) {
51
245k
        return;
52
245k
    }
53
18.8M
    try {
54
18.8M
        close();
55
18.8M
    } catch (const Exception& e) {
56
0
        LOG(WARNING) << "Exception occurs when expr context deconstruct: " << e.to_string();
57
0
    }
58
18.8M
}
59
60
1.10M
Status VExprContext::execute(Block* block, int* result_column_id) {
61
1.10M
    Status st;
62
1.10M
    RETURN_IF_CATCH_EXCEPTION({
63
1.10M
        st = _root->execute(this, block, result_column_id);
64
1.10M
        _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
1.10M
        if (st.ok() && _last_result_column_id != -1) {
67
1.10M
            block->get_by_position(*result_column_id).column->sanity_check();
68
1.10M
            RETURN_IF_ERROR(
69
1.10M
                    block->get_by_position(*result_column_id).check_type_and_column_match());
70
1.10M
        }
71
1.10M
    });
72
1.10M
    return st;
73
1.10M
}
74
75
1.91M
Status VExprContext::execute(const Block* block, ColumnPtr& result_column) {
76
1.91M
    Status st;
77
1.91M
    RETURN_IF_CATCH_EXCEPTION(
78
1.91M
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
79
1.91M
    return st;
80
1.91M
}
81
82
25.4k
Status VExprContext::execute(const Block* block, ColumnWithTypeAndName& result_data) {
83
25.4k
    Status st;
84
25.4k
    ColumnPtr result_column;
85
25.4k
    RETURN_IF_CATCH_EXCEPTION(
86
25.4k
            { st = _root->execute_column(this, block, nullptr, block->rows(), result_column); });
87
25.5k
    RETURN_IF_ERROR(st);
88
25.5k
    result_data.column = result_column;
89
25.5k
    result_data.type = execute_type(block);
90
25.5k
    result_data.name = _root->expr_name();
91
25.5k
    return Status::OK();
92
25.5k
}
93
94
804k
DataTypePtr VExprContext::execute_type(const Block* block) {
95
804k
    return _root->execute_type(block);
96
804k
}
97
98
1.03M
Status VExprContext::execute_const_expr(ColumnWithTypeAndName& result) {
99
1.03M
    Status st;
100
1.03M
    RETURN_IF_CATCH_EXCEPTION(
101
1.03M
            { st = _root->execute_column(this, nullptr, nullptr, 1, result.column); });
102
1.03M
    RETURN_IF_ERROR(st);
103
1.03M
    result.type = _root->execute_type(nullptr);
104
1.03M
    result.name = _root->expr_name();
105
1.03M
    return Status::OK();
106
1.03M
}
107
108
778k
[[nodiscard]] const std::string& VExprContext::expr_name() const {
109
778k
    return _root->expr_name();
110
778k
}
111
112
0
bool VExprContext::is_blockable() const {
113
0
    return _root->is_blockable();
114
0
}
115
116
5.02M
Status VExprContext::prepare(RuntimeState* state, const RowDescriptor& row_desc) {
117
5.02M
    _prepared = true;
118
5.02M
    Status st;
119
5.02M
    RETURN_IF_CATCH_EXCEPTION({ st = _root->prepare(state, row_desc, this); });
120
5.02M
    return st;
121
5.02M
}
122
123
5.02M
Status VExprContext::open(RuntimeState* state) {
124
5.02M
    DCHECK(_prepared);
125
5.02M
    if (_opened) {
126
46
        return Status::OK();
127
46
    }
128
5.02M
    _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
5.02M
    FunctionContext::FunctionStateScope scope =
132
5.02M
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
133
5.02M
    Status st;
134
5.02M
    RETURN_IF_CATCH_EXCEPTION({ st = _root->open(state, this, scope); });
135
5.02M
    return st;
136
5.02M
}
137
138
18.8M
void VExprContext::close() {
139
    // Sometimes expr context may not have a root, then it need not call close
140
18.8M
    if (_root == nullptr) {
141
0
        return;
142
0
    }
143
18.8M
    FunctionContext::FunctionStateScope scope =
144
18.8M
            _is_clone ? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
145
18.8M
    _root->close(this, scope);
146
18.8M
}
147
148
13.7M
Status VExprContext::clone(RuntimeState* state, VExprContextSPtr& new_ctx) {
149
18.4E
    DCHECK(_prepared) << "expr context not prepared";
150
13.7M
    DCHECK(_opened);
151
13.7M
    DCHECK(new_ctx.get() == nullptr);
152
153
13.7M
    new_ctx = std::make_shared<VExprContext>(_root);
154
13.7M
    for (auto& _fn_context : _fn_contexts) {
155
1.14M
        new_ctx->_fn_contexts.push_back(_fn_context->clone());
156
1.14M
    }
157
158
13.7M
    new_ctx->_is_clone = true;
159
13.7M
    new_ctx->_prepared = true;
160
13.7M
    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
13.7M
    new_ctx->_ann_range_search_runtime = this->_ann_range_search_runtime;
164
165
13.7M
    return _root->open(state, new_ctx.get(), FunctionContext::THREAD_LOCAL);
166
13.7M
}
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
581k
                                            const std::vector<DataTypePtr>& arg_types) {
176
581k
    _fn_contexts.push_back(FunctionContext::create_context(state, return_type, arg_types));
177
581k
    _fn_contexts.back()->set_check_overflow_for_decimal(state->check_overflow_for_decimal());
178
581k
    _fn_contexts.back()->set_enable_strict_mode(state->enable_strict_mode());
179
581k
    return static_cast<int>(_fn_contexts.size()) - 1;
180
581k
}
181
182
18.1k
Status VExprContext::evaluate_inverted_index(uint32_t segment_num_rows) {
183
18.1k
    Status st;
184
18.1k
    RETURN_IF_CATCH_EXCEPTION({ st = _root->evaluate_inverted_index(this, segment_num_rows); });
185
18.1k
    return st;
186
18.1k
}
187
188
17.7k
bool VExprContext::all_expr_inverted_index_evaluated() {
189
17.7k
    return _index_context->has_index_result_for_expr(_root.get());
190
17.7k
}
191
192
53
Status VExprContext::filter_block(VExprContext* vexpr_ctx, Block* block) {
193
53
    if (vexpr_ctx == nullptr || block->rows() == 0) {
194
0
        return Status::OK();
195
0
    }
196
53
    ColumnPtr filter_column;
197
53
    RETURN_IF_ERROR(vexpr_ctx->execute(block, filter_column));
198
53
    size_t filter_column_id = block->columns();
199
53
    block->insert({filter_column, vexpr_ctx->execute_type(block), "filter_column"});
200
53
    vexpr_ctx->_memory_usage = filter_column->allocated_bytes();
201
53
    return Block::filter_block(block, filter_column_id, filter_column_id);
202
53
}
203
204
Status VExprContext::filter_block(const VExprContextSPtrs& expr_contexts, Block* block,
205
1.34M
                                  size_t column_to_keep) {
206
1.34M
    if (expr_contexts.empty() || block->rows() == 0) {
207
1.32M
        return Status::OK();
208
1.32M
    }
209
210
16.0k
    ColumnNumbers columns_to_filter(column_to_keep);
211
16.0k
    std::iota(columns_to_filter.begin(), columns_to_filter.end(), 0);
212
213
16.0k
    return execute_conjuncts_and_filter_block(expr_contexts, block, columns_to_filter,
214
16.0k
                                              static_cast<int>(column_to_keep));
215
1.34M
}
216
217
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
218
                                       const std::vector<IColumn::Filter*>* filters, Block* block,
219
2.25k
                                       IColumn::Filter* result_filter, bool* can_filter_all) {
220
2.25k
    return execute_conjuncts(ctxs, filters, false, block, result_filter, can_filter_all);
221
2.25k
}
222
223
Status VExprContext::execute_filter(const Block* block, uint8_t* __restrict result_filter_data,
224
151k
                                    size_t rows, bool accept_null, bool* can_filter_all) {
225
151k
    return _root->execute_filter(this, block, result_filter_data, rows, accept_null,
226
151k
                                 can_filter_all);
227
151k
}
228
229
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& ctxs,
230
                                       const std::vector<IColumn::Filter*>* filters,
231
                                       bool accept_null, const Block* block,
232
255k
                                       IColumn::Filter* result_filter, bool* can_filter_all) {
233
255k
    size_t rows = block->rows();
234
255k
    DCHECK_EQ(result_filter->size(), rows);
235
255k
    *can_filter_all = false;
236
255k
    auto* __restrict result_filter_data = result_filter->data();
237
255k
    for (const auto& ctx : ctxs) {
238
151k
        RETURN_IF_ERROR(
239
151k
                ctx->execute_filter(block, result_filter_data, rows, accept_null, can_filter_all));
240
151k
        if (*can_filter_all) {
241
38.9k
            return Status::OK();
242
38.9k
        }
243
151k
    }
244
216k
    if (filters != nullptr) {
245
31
        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
31
    }
257
216k
    return Status::OK();
258
216k
}
259
260
Status VExprContext::execute_conjuncts(const VExprContextSPtrs& conjuncts, const Block* block,
261
361
                                       ColumnUInt8& null_map, IColumn::Filter& filter) {
262
361
    const auto& rows = block->rows();
263
361
    if (rows == 0) {
264
0
        return Status::OK();
265
0
    }
266
361
    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
361
    auto* final_null_map = null_map.get_data().data();
272
361
    auto* final_filter_ptr = filter.data();
273
274
361
    for (const auto& conjunct : conjuncts) {
275
64
        ColumnPtr result_column;
276
64
        RETURN_IF_ERROR(conjunct->execute(block, result_column));
277
64
        auto [filter_column, is_const] = unpack_if_const(result_column);
278
64
        const auto* nullable_column = assert_cast<const ColumnNullable*>(filter_column.get());
279
64
        if (!is_const) {
280
55
            const ColumnPtr& nested_column = nullable_column->get_nested_column_ptr();
281
55
            const IColumn::Filter& result =
282
55
                    assert_cast<const ColumnUInt8&>(*nested_column).get_data();
283
55
            const auto* __restrict filter_data = result.data();
284
55
            const auto* __restrict null_map_data = nullable_column->get_null_map_data().data();
285
55
            DCHECK_EQ(rows, nullable_column->size());
286
287
632
            for (size_t i = 0; i != rows; ++i) {
288
                // null and null    => null
289
                // null and true    => null
290
                // null and false   => false
291
577
                final_null_map[i] = (final_null_map[i] & (null_map_data[i] | filter_data[i])) |
292
577
                                    (null_map_data[i] & (final_null_map[i] | final_filter_ptr[i]));
293
577
                final_filter_ptr[i] = final_filter_ptr[i] & filter_data[i];
294
577
            }
295
55
        } else {
296
9
            bool filter_data = nullable_column->get_bool(0);
297
9
            bool null_map_data = nullable_column->is_null_at(0);
298
28
            for (size_t i = 0; i != rows; ++i) {
299
                // null and null    => null
300
                // null and true    => null
301
                // null and false   => false
302
19
                final_null_map[i] = (final_null_map[i] & (null_map_data | filter_data)) |
303
19
                                    (null_map_data & (final_null_map[i] | final_filter_ptr[i]));
304
19
                final_filter_ptr[i] = final_filter_ptr[i] & filter_data;
305
19
            }
306
9
        }
307
64
    }
308
361
    return Status::OK();
309
361
}
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
17.3k
                                                        int column_to_keep) {
316
17.3k
    IColumn::Filter result_filter(block->rows(), 1);
317
17.3k
    bool can_filter_all;
318
319
17.3k
    _reset_memory_usage(ctxs);
320
321
17.3k
    RETURN_IF_ERROR(
322
17.3k
            execute_conjuncts(ctxs, nullptr, false, block, &result_filter, &can_filter_all));
323
324
    // Accumulate the usage of `result_filter` into the first context.
325
17.3k
    if (!ctxs.empty()) {
326
17.3k
        ctxs[0]->_memory_usage += result_filter.allocated_bytes();
327
17.3k
    }
328
17.3k
    if (can_filter_all) {
329
31.2k
        for (auto& col : columns_to_filter) {
330
31.2k
            auto& column = block->get_by_position(col).column;
331
31.2k
            if (column->is_exclusive()) {
332
28.7k
                column->assert_mutable()->clear();
333
28.7k
            } else {
334
2.57k
                column = column->clone_empty();
335
2.57k
            }
336
31.2k
        }
337
10.0k
    } else {
338
10.0k
        try {
339
10.0k
            Block::filter_block_internal(block, columns_to_filter, result_filter);
340
10.0k
        } 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
10.0k
    }
354
17.3k
    Block::erase_useless_column(block, column_to_keep);
355
17.3k
    return Status::OK();
356
17.3k
}
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
11.4k
                                                        IColumn::Filter& filter) {
362
11.4k
    _reset_memory_usage(ctxs);
363
11.4k
    filter.resize_fill(block->rows(), 1);
364
11.4k
    bool can_filter_all;
365
11.4k
    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
11.4k
    if (!ctxs.empty()) {
369
11.4k
        ctxs[0]->_memory_usage += filter.allocated_bytes();
370
11.4k
    }
371
11.4k
    if (can_filter_all) {
372
5.97k
        for (auto& col : columns_to_filter) {
373
5.97k
            auto& column = block->get_by_position(col).column;
374
5.97k
            if (column->is_exclusive()) {
375
5.97k
                column->assert_mutable()->clear();
376
5.97k
            } else {
377
1
                column = column->clone_empty();
378
1
            }
379
5.97k
        }
380
8.13k
    } else {
381
8.13k
        RETURN_IF_CATCH_EXCEPTION(Block::filter_block_internal(block, columns_to_filter, filter));
382
8.13k
    }
383
384
11.4k
    Block::erase_useless_column(block, column_to_keep);
385
11.4k
    return Status::OK();
386
11.4k
}
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
169k
        bool do_projection) {
396
169k
    auto rows = input_block.rows();
397
169k
    ColumnsWithTypeAndName result_columns;
398
169k
    _reset_memory_usage(output_vexpr_ctxs);
399
400
778k
    for (const auto& vexpr_ctx : output_vexpr_ctxs) {
401
778k
        ColumnPtr result_column;
402
778k
        RETURN_IF_ERROR(vexpr_ctx->execute(&input_block, result_column));
403
404
778k
        auto type = vexpr_ctx->execute_type(&input_block);
405
778k
        const auto& name = vexpr_ctx->expr_name();
406
407
778k
        vexpr_ctx->_memory_usage += result_column->allocated_bytes();
408
778k
        if (do_projection) {
409
6.97k
            result_columns.emplace_back(result_column->clone_resized(rows), type, name);
410
411
771k
        } else {
412
771k
            result_columns.emplace_back(result_column, type, name);
413
771k
        }
414
778k
    }
415
169k
    *output_block = {result_columns};
416
169k
    return Status::OK();
417
169k
}
418
419
198k
void VExprContext::_reset_memory_usage(const VExprContextSPtrs& contexts) {
420
198k
    std::for_each(contexts.begin(), contexts.end(),
421
816k
                  [](auto&& context) { context->_memory_usage = 0; });
422
198k
}
423
424
20.7k
void VExprContext::prepare_ann_range_search(const doris::VectorSearchUserParams& params) {
425
20.7k
    if (_root == nullptr) {
426
0
        return;
427
0
    }
428
429
20.7k
    _root->prepare_ann_range_search(params, _ann_range_search_runtime, _suitable_for_ann_index);
430
18.4E
    VLOG_DEBUG << fmt::format("Prepare ann range search result {}, _suitable_for_ann_index {}",
431
18.4E
                              this->_ann_range_search_runtime.to_string(),
432
18.4E
                              this->_suitable_for_ann_index);
433
20.7k
    return;
434
20.7k
}
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
        roaring::Roaring& row_bitmap, segment_v2::AnnIndexStats& ann_index_stats,
443
17.8k
        bool enable_result_cache) {
444
17.8k
    if (_root == nullptr) {
445
0
        return Status::OK();
446
0
    }
447
448
17.8k
    RETURN_IF_ERROR(_root->evaluate_ann_range_search(
449
17.8k
            _ann_range_search_runtime, cid_to_index_iterators, idx_to_cid, column_iterators,
450
17.8k
            row_bitmap, ann_index_stats, enable_result_cache));
451
452
17.8k
    if (!_root->ann_range_search_executedd()) {
453
17.7k
        return Status::OK();
454
17.7k
    }
455
456
73
    if (!_root->ann_dist_is_fulfilled()) {
457
        // Do not perform index scan in this case.
458
9
        return Status::OK();
459
9
    }
460
461
64
    auto src_col_idx = _ann_range_search_runtime.src_col_idx;
462
64
    auto slot_ref_map_it = common_expr_to_slotref_map.find(this);
463
64
    if (slot_ref_map_it == common_expr_to_slotref_map.end()) {
464
1
        return Status::OK();
465
1
    }
466
63
    auto& slot_ref_map = slot_ref_map_it->second;
467
63
    ColumnId cid = idx_to_cid[src_col_idx];
468
63
    if (slot_ref_map.find(cid) == slot_ref_map.end()) {
469
6
        return Status::OK();
470
6
    }
471
57
    const VExpr* slot_ref_expr_addr = slot_ref_map.find(cid)->second;
472
57
    _index_context->set_true_for_index_status(slot_ref_expr_addr, idx_to_cid[cid]);
473
474
57
    VLOG_DEBUG << fmt::format(
475
15
            "Evaluate ann range search for expr {}, src_col_idx {}, cid {}, row_bitmap "
476
15
            "cardinality {}",
477
15
            _root->debug_string(), src_col_idx, cid, row_bitmap.cardinality());
478
57
    return Status::OK();
479
63
}
480
481
289k
uint64_t VExprContext::get_digest(uint64_t seed) const {
482
289k
    return _root->get_digest(seed);
483
289k
}
484
485
650k
double VExprContext::execute_cost() const {
486
650k
    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
650k
    return _root->execute_cost();
492
650k
}
493
494
} // namespace doris